home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 October: Mac OS SDK / Dev.CD Oct 97 SDK1.toast / Development Kits (Disc 1) / QuickDraw GX / Programming Stuff / Sample Code / Printing Samples / Printer Drivers… / ImageWriter--Chooser snooper / NewApp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-15  |  75.1 KB  |  2,658 lines  |  [TEXT/MPS ]

  1. /*
  2.     copyright © 1991-1996 Apple Computer Inc.  All rights reserved.
  3.     
  4.     NewApp.c
  5.     This file contains all new API implementations for the ImageWriter driver.
  6.     
  7.     Modification history
  8.     03/19/91        TED                New file today
  9.     04/23/91        Sam Weiss        Changed Inherit to Forward
  10.     05/29/91        TED                Added manual feed and faster mode support
  11.     12/20/93        dmh                Sync'd with the shipping 1.0b3 GX driver.
  12.     03/24/94        Ken Hittleman    Updated manual feed to use gxTrayFeedInfo
  13.     03/30/94        Ken Hittleman    Added call to paper matching CheckStatus when switching to auto-feed
  14.     07/05/94        Ken Hittleman    Removed set color and page size from IW I path, which blew cookies on it
  15.     08/26/94        dmh                Sync'd with the shipping 1.0.1 GX driver.
  16.      6/14/96        cn                Updated to support Universal Interfaces 2.1.
  17. */
  18.  
  19. #include <memory.h>
  20. #include <Errors.h>
  21. #include <ToolUtils.h>
  22. #include <Resources.h>
  23. #include <Packages.h>
  24. #include <GXPrinterDrivers.h>
  25. #include <GXPrinting.h>
  26. #include <FixMath.h>
  27. #include <GXMath.h>
  28. #include <Graphics Routines.h>
  29. #include <GraphicsLibraries.h>
  30. #include <FontLibrary.h>
  31. #include <GXLayout.h>
  32. #include <GXExceptions.h>
  33. #include <PrintingLibraries.h>
  34.  
  35. #include "CommonDefines.h"
  36.  
  37. /* ------------------------------------------------------------------------------------    */
  38. /*    INTERNAL DEFINES                                                                    */
  39. /* ------------------------------------------------------------------------------------    */    
  40.  
  41. // positive error for aborting job and placing on hold
  42. #define kPutJobOnHoldErr            3
  43.  
  44. // timeout (in ticks) for the initial query
  45. #define kQueryTimeout                (7*60);
  46.  
  47. // things this specific driver puts into the DTP config file
  48. #define    kImageWriterConfigType        'ifig'
  49. #define kImageWriterConfigID        (0)            
  50. typedef struct
  51.     {
  52.         Boolean    hasColorRibbon;
  53.         Boolean    hasSheetFeeder;
  54.         Boolean    isImageWriterII;        // is this an ImageWriter II, or an older model?
  55.     } ImageWriterConfigRecord, *ImageWriterConfigPtr, ** ImageWriterConfigHandle;
  56.     
  57. /* Define special characters needed */
  58. #define ESCAPE                (char) 27
  59.  
  60. /* A record to hold a set margins command */
  61. typedef struct SetMarginsRecord
  62.     {
  63.     char        cEscape;                    // ESCAPE character
  64.     char        cCommand;                    // Set Margins command character
  65.     char        cIndentDistance[4];            // number of dots to indent
  66.     } SetMarginsRecord, *SetMarginsPtr;
  67. #define kSetMarginsCommand    (char)'F'        // ImageWriter II uses 'F' for tabbing
  68. #define kSetMarginsSize        6
  69.  
  70. /*     Define a record that can hold one scan line's worth of data, 1280 will
  71.     only happen at 160 dpi. and 14 inch wide paper.   */
  72. typedef struct ScanLineRecord
  73.     {
  74.     char            cColorEscape;                    // ESCAPE character
  75.     char            cSetColorCommand;                // Set color command
  76.     char            cColor;                            // The color
  77.     char            cEscape;                        // ESCAPE character
  78.     char            cCommand;                        // 'enter graphics' command
  79.     char            cLineLength[4];                    // number of dots to print
  80.     char            iTheData[2240];                    // Bits for the data, enough for one line's worth
  81.     } ScanLineRecord, *ScanLinePtr;
  82. #define kGraphicsCommand    (char)'G'        /* graphics printing command */
  83. #define kRepeatGroup        (char)'V'        /* repeat group character */
  84. #define kSetColorCommand     (char)'K'        /* Set color command */
  85. #define kGroupSize            6                /* Size of one group header */
  86.  
  87. #define kScanLineSize         3                /* NOTE: this is just the header size! */
  88.  
  89. #define kStatusCommand        "\033?"            /* request device status/config */
  90.  
  91. // Status flags for PAP status queries
  92. #define    kColorRibbonBit        0
  93. #define kSheetFeederBit        1
  94. #define kPaperOutBit        2
  95. #define kCoverOpenBit        3
  96. #define kOffLineBit            4
  97. #define kPaperJamBit        5
  98. #define kPrinterFaultBit    6
  99. #define kHeadMovingBit        7
  100. #define kPrinterBusyBit        8
  101.  
  102. #define kOutOfPaperMask            (  (0x8000 >> kPaperJamBit) | (0x8000 >> kCoverOpenBit) | (0x8000 >> kOffLineBit) )
  103. #define kPrinterOfflineMask        (  (0x8000 >> kOffLineBit) )
  104. #define kPrinterBusyMask        (  (0x8000 >> kPrinterBusyBit) )
  105. #define kHeadMovingMask            (  (0x8000 >> kHeadMovingBit) )
  106.  
  107. //<FF>
  108. /* ------------------------------------------------------------------------------------    */
  109. /*    INTERNAL ROUTINES                                                                */
  110. /* ------------------------------------------------------------------------------------    */
  111. void Long2Dec(long aLong, Ptr emitHere)
  112. /*
  113.     Converts a long into an ASCII string, padded with leading zeros.
  114. */
  115. {    
  116.     char    aString[10];
  117.     short    i, actualWidth, strLength;
  118.     
  119.     NumToString(aLong, (unsigned char *) aString);
  120.     
  121.     // Get the width of the string, check for being too small
  122.     strLength = aString[0];
  123.     actualWidth = strLength;
  124.     if (actualWidth < 4)
  125.         actualWidth = 4;
  126.         
  127.     // output the string, padding with the requested character
  128.     strLength = actualWidth-strLength;
  129.     for (i = 0; i < actualWidth; ++i)
  130.         {
  131.         *emitHere++ = (i < strLength) 
  132.             ? '0' : aString[(i+1)-(strLength)];
  133.         }
  134.         
  135. } // Long2Dec
  136.  
  137.  
  138. //<FF>
  139. /* ------------------------------------------------------------------------------------    */
  140. Boolean PrinterHasColorRibbon(gxPrinter thePrinter)
  141. /*
  142.     Returns true if the config file says that the printer is blessed with a color ribbon,
  143.     false if it is a black and white ribbon.
  144. */
  145. {
  146.     Boolean                        hasColor = true;
  147.     Str32                        deviceName;
  148.     OSErr                        anErr;
  149.     ImageWriterConfigHandle        configHandle;
  150.     
  151.     // if not formatting to a particular device, assume color ribbon, for widest range of colorSpaces
  152.     GXGetPrinterName(thePrinter, deviceName);
  153.     if (deviceName[0] != 0)
  154.         {
  155.         // if we are going to a particular device, assume no color, as that is more common
  156.         hasColor = false;
  157.         
  158.         anErr = GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, &(Handle)configHandle);
  159.         if (anErr == noErr)
  160.             {
  161.             hasColor = (**configHandle).hasColorRibbon;
  162.             DisposHandle((Handle) configHandle);
  163.             }
  164.         }
  165.     
  166.     return(hasColor);
  167.     
  168. } // PrinterHasColorRibbon
  169.  
  170.  
  171. //<FF>
  172. /* ------------------------------------------------------------------------------------    */
  173. gxViewDevice    NewDeviceResolutionViewDevice(void)
  174. /*
  175.     This routine creates a viewDevice and gives it a scale factor in it's mapping
  176.     appropriate for this device (144 dpi in the case of the IW)
  177. */
  178. {
  179.     gxViewDevice        vd;
  180.     
  181.     // create the viewDevices with a fake bitmap
  182.     {
  183.     gxShape        tempBitmap;
  184.     gxBitmap        aBitmap;
  185.     
  186.     aBitmap.pixelSize     = 1;
  187.     aBitmap.rowBytes     = 0;
  188.     aBitmap.width         = 0;
  189.     aBitmap.height         = 0;
  190.     aBitmap.image         = (char*)gxMissingImagePointer;
  191.     aBitmap.space         = gxNoSpace;
  192.     aBitmap.set         = nil;
  193.     aBitmap.profile     = nil;
  194.     
  195.     tempBitmap = GXNewBitmap(&aBitmap, nil);
  196.     vd = GXNewViewDevice(gxScreenViewDevices, tempBitmap);
  197.     GXDisposeShape(tempBitmap);
  198.     }
  199.  
  200.     // setup a mapping for a 144 (2X) viewDevice
  201.     {
  202.     gxMapping    vdMapping;
  203.     
  204.     ResetMapping(&vdMapping);
  205.     ScaleMapping(&vdMapping, ff(2), ff(2), ff(0), ff(0));
  206.     
  207.     GXSetViewDeviceMapping(vd, &vdMapping);
  208.     }
  209.     
  210.     return(vd);
  211.     
  212. } // NewDeviceResolutionViewDevice
  213.  
  214. //<FF>
  215. /* ------------------------------------------------------------------------------------    */
  216. Boolean    JobIsBest(long *imagewriterOptions)
  217. /*
  218.     Returns true if the current job is a final quality mode job, else returns false.
  219.     Also, returns the imagewriter rendering options.
  220. */
  221. {
  222.     Boolean            isFinal;
  223.     gxQualityInfo    jobQualitySettings;
  224.     long            itemSize = sizeof(jobQualitySettings);
  225.     OSErr            status;
  226.     Collection        jobCollection;
  227.     
  228.     // cache the collection
  229.     jobCollection = GXGetJobCollection(GXGetJob());
  230.     
  231.     // find out the info
  232.         
  233.     isFinal = false;
  234.     
  235.     status = GetCollectionItem(jobCollection, 
  236.                                     gxQualityTag, gxPrintingTagID, 
  237.                                     &itemSize, &jobQualitySettings);
  238.     
  239.     if ( (status == noErr) && (jobQualitySettings.currentQuality == (jobQualitySettings.qualityCount-1)) )
  240.         isFinal = true;
  241.     
  242.     ncheck( status );
  243.  
  244.     // we default to super res
  245.     *imagewriterOptions = kSuperRes;
  246.     itemSize = sizeof(imagewriterOptions);
  247.     status = GetCollectionItem(jobCollection, 
  248.                                     DriverCreator, 0, 
  249.                                     &itemSize, imagewriterOptions);
  250.                 
  251.     // and return the job quality mode
  252.     return(isFinal);
  253.     
  254. } // JobIsBest
  255.  
  256.  
  257. //<FF>
  258. /* ------------------------------------------------------------------------------------    */
  259.  
  260. OSErr    DoTheQuery(unsigned short * statusReturn, Boolean papStatus)
  261. /*
  262.     Returns in statusString the current status for the printer.  Returns various
  263.     errors from IO package if the printer's status could not be found.
  264. */
  265. {
  266.     OSErr                anErr = noErr;
  267.     long                statusLength;                    // status string size
  268.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  269.  
  270.     // default to a clear status
  271.     *statusReturn = 0;
  272.  
  273.     // send the query
  274.     if (papStatus)
  275.         {
  276.         char    statusString[255];                // returned string
  277.         
  278.         // According to the old IW driver, sometimes it will return all of the bits
  279.         // set.  This is an error, but we can just try again.
  280.         do {
  281.             statusLength = 255;
  282.             anErr = Send_GXGetDeviceStatus(nil, 0, statusString, &statusLength, nil);
  283.             } while ( (anErr == noErr) && (statusString[0] == 0xFF) );
  284.         
  285.         // return the printer status bits in the PAP case
  286.         *statusReturn = *(unsigned short*)&statusString[0];
  287.         }
  288.     else
  289.         {
  290.         char    statusString[8];                // returned string
  291.  
  292.         if ((**hGlobals).isImageWriterII)
  293.             {
  294.             statusLength = 8; // max number of characters to get back
  295.             anErr = Send_GXGetDeviceStatus(kStatusCommand, 2, statusString, &statusLength, "\p\n");
  296.                 
  297.             if ( anErr == gxAioTimeout)
  298.                 {
  299.                 *statusReturn = kPrinterOfflineMask;
  300.                 anErr = noErr;
  301.                 }
  302.             else
  303.                 {
  304.                 if (anErr == noErr)
  305.                     {
  306.                     // generate printer status bits in the serial case
  307.                     if (statusString[4] == 'C')
  308.                         *statusReturn |= 0x8000 >> kColorRibbonBit;
  309.                     if ( (statusString[5] == 'F') || (statusString[4] == 'F') )
  310.                         *statusReturn |= 0x8000 >> kSheetFeederBit;
  311.                     }
  312.                 }
  313.             }
  314.         }
  315.         
  316.     nrequire(anErr, Send_GXGetDeviceStatus);
  317.  
  318. // FALL THROUGH EXCEPTION HANDLING    
  319. Send_GXGetDeviceStatus:
  320.     
  321.     return(anErr);
  322.  
  323. } // DoTheQuery
  324.  
  325. //<FF>
  326. /* ------------------------------------------------------------------------------------    */
  327. OSErr FetchStatusString(unsigned short * statusReturn, Boolean papStatus, Boolean doRetry)
  328. /*
  329.     Returns in statusString the current status for the printer.  Returns various
  330.     errors from IO package if the printer's status could not be found.
  331.     
  332.     Handles reporting error conditions to the user.
  333. */
  334. {
  335.     OSErr            anErr;
  336.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  337.     
  338.     anErr = DoTheQuery(statusReturn, papStatus);        
  339.     nrequire(anErr, Send_GXGetDeviceStatus);
  340.     
  341.     // printer offline?
  342.     if (     
  343.         (doRetry) &&
  344.         ( ((*statusReturn) & kPrinterOfflineMask) != 0 )  
  345.         )
  346.         {
  347.         gxStatusRecord        theStat;
  348.         gxStatusRecord        *pStat = &theStat;
  349.         Boolean                printerIsFixed = false;
  350.         
  351.         pStat->statusOwner    = 'drvr';
  352.         pStat->statResId     = kDriverStatus;        
  353.         pStat->statResIndex = kCheckOnline;            
  354.         pStat->bufferLen      = 0;
  355.         pStat->dialogResult = 0;
  356.         
  357.  
  358.         // keep sending the user the alert until either
  359.         //  a) the problem resolves itself
  360.         //  b) the user responds via the dialog
  361.         //  c) some other (fatal) error happens
  362.         do
  363.             {
  364.             
  365.             // tell the user
  366.             anErr = GXAlertTheUser(pStat);
  367.             
  368.             // based on the user's response, continue or cancel
  369.             switch (pStat->dialogResult)
  370.                 {
  371.                 case ok:
  372.                     // retry
  373.                     break;
  374.                     
  375.                 case cancel:
  376.                     anErr = gxPrUserAbortErr;
  377.                     break;
  378.                     
  379.                 case 3:
  380.                     anErr = kPutJobOnHoldErr;
  381.                     break;
  382.                 }
  383.                 
  384.             // error to return from next idle
  385.             (**hGlobals).idleError = anErr;
  386.  
  387.             // if printer got suddenly turned online, do an OK
  388.             if ( (anErr == noErr) && ((papStatus) || (pStat->dialogResult == ok)) )
  389.                 {
  390.                 pStat->dialogResult = 0;
  391.                 (void) DoTheQuery(statusReturn, papStatus);        
  392.                 if (     
  393.                     ( ((*statusReturn) & kPrinterOfflineMask) == 0 ) 
  394.                     )
  395.                     {
  396.                     printerIsFixed = true;
  397.                     pStat->dialogResult = ok;
  398.                     anErr = noErr;
  399.                     }
  400.                 }
  401.                 
  402.             } while ((anErr == noErr) && (pStat->dialogResult == 0));
  403.  
  404.         // printer is okay -- no error
  405.         if (printerIsFixed)
  406.             anErr = noErr;
  407.         
  408.         // display "sending data to the printer" message
  409.         if (anErr == noErr)
  410.             anErr = GXReportStatus(kDriverStatus, kSendingData);
  411.         }
  412.  
  413. // FALL THROUGH EXCEPTION HANDLING    
  414. Send_GXGetDeviceStatus:
  415.     
  416.     return(anErr);
  417.     
  418. } // FetchStatusString
  419.  
  420. //<FF>
  421. /* ------------------------------------------------------------------------------------    */
  422. OSErr UpdateConfiguration(void)
  423. /*
  424.     This routine queries the printer for its hardware configuration (color ribbon and
  425.     sheet feeder options), and stores that info into the configuration file.
  426. */
  427. {
  428.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  429.     Str32                        deviceName;
  430.     OSErr                        anErr = noErr;
  431.     ImageWriterConfigHandle        configHandle;
  432.     ImageWriterConfigPtr        configPtr;
  433.     Boolean                        isImageWriterII = false;
  434.     ResType                        commType;
  435.     
  436.         
  437.     // find out what we are printing to, and how we are connected
  438.     GXGetPrinterName(GXGetJobOutputPrinter(GXGetJob()), deviceName);
  439.     anErr = GXFetchDTPData(deviceName, gxDeviceCommunicationsType, gxDeviceCommunicationsID, (Handle*)&configHandle);
  440.     nrequire(anErr, FetchCommType);
  441.     commType = **(ResType**)configHandle;
  442.     DisposHandle((Handle) configHandle);
  443.     
  444.     
  445.     // store away the communications type for future use
  446.     {
  447.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  448.     
  449.     (**hGlobals).commType = commType;
  450.     }
  451.     
  452.     // find out the original configuration
  453.     if (GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle*)&configHandle) == noErr)
  454.         {
  455.         // remember if we thought we had an IW2 when we started
  456.         configPtr = *configHandle;
  457.         (**hGlobals).isImageWriterII = isImageWriterII = configPtr->isImageWriterII;
  458.         DisposeHandle((Handle) configHandle);
  459.  
  460.         // if we aren't an ImageWriter II, bail out now - because the timeout takes two minutes!
  461.         if (!isImageWriterII)
  462.             return(noErr);            
  463.         }
  464.     else
  465.         {        
  466.         // if we don't know yet, assume IW2 for PAP else Serial
  467.         if (commType == 'PPTL')
  468.             isImageWriterII = true;
  469.             
  470.         // Assume IW 2 so we do the query for real
  471.         (**hGlobals).isImageWriterII = true;
  472.         }
  473.         
  474.     // make a handle to hold our configuration information for the printer
  475.     configHandle = (ImageWriterConfigHandle) NewHandle(sizeof(ImageWriterConfigRecord) );
  476.     anErr = MemError();
  477.     nrequire(anErr, NewHandle);
  478.     
  479.     // setup the default for the device - in case the query fails
  480.     configPtr = *configHandle;
  481.     configPtr->hasColorRibbon = false;
  482.     configPtr->hasSheetFeeder = false;
  483.     configPtr->isImageWriterII = true;
  484.     
  485.     // send initial data first to make sure IO handshaking is working,
  486.     // to load the first sheet of paper into the feeder (if any),
  487.     // and to take up "gear lash" in the device.  This is copied from
  488.     // what the old driver did.  Not doing this will cause the sheet
  489.     // feeder not to feed the initial page of data.
  490.     {
  491.     char    sendBuffer[11];
  492.     
  493.     // <CR>
  494.     sendBuffer[0] = 0x0D;
  495.     
  496.     // linefeed size = 18/144th
  497.     sendBuffer[1] = ESCAPE;
  498.     sendBuffer[2] = 'T';
  499.     sendBuffer[3] = '1';
  500.     sendBuffer[4] = '8';
  501.     
  502.     // reverse line feed
  503.     sendBuffer[5] = ESCAPE;
  504.     sendBuffer[6] = 'r';
  505.     sendBuffer[7] = 0x0A;
  506.     
  507.     // forward line feed
  508.     sendBuffer[8] = ESCAPE;
  509.     sendBuffer[9] = 'f';
  510.     sendBuffer[10] = 0x0A;
  511.     
  512.     anErr = Send_GXWriteData(sendBuffer, 11);
  513.     nrequire(anErr, Failed_SendInitialData);
  514.     }
  515.     
  516.     {
  517.     unsigned short    statusReturn;
  518.     
  519.     // query the device
  520.     if ((isImageWriterII) && (commType == 'SPTL') )
  521.         (**hGlobals).idleTimeout = TickCount() + kQueryTimeout;
  522.     anErr = FetchStatusString(&statusReturn, (commType == 'PPTL'), isImageWriterII);
  523.     if ( (anErr == noErr) && ( (statusReturn & kPrinterOfflineMask) != 0 )  )
  524.         anErr = gxAioTimeout;
  525.     (**hGlobals).idleTimeout = 0;
  526.     (void) GXReportStatus(kDriverStatus, kSendingData);
  527.     
  528.     // and scan the string looking for information about printer kind and options
  529.     configPtr = *configHandle;
  530.     if ( anErr == gxAioTimeout )
  531.         {
  532.         // if we timeout and we don't know the printer kind - assume IW1
  533.         if (!isImageWriterII)
  534.             {
  535.             anErr = noErr;
  536.             isImageWriterII = configPtr->isImageWriterII = false;
  537.             }
  538.         }
  539.     else
  540.         {
  541.         isImageWriterII = true;
  542.         configPtr->hasColorRibbon = (statusReturn & (0x8000 >> kColorRibbonBit)) != 0;
  543.         configPtr->hasSheetFeeder = (statusReturn & (0x8000 >> kSheetFeederBit)) != 0;
  544.         }
  545.     nrequire(anErr, FetchStatusString);
  546.     }
  547.     
  548.     // Remember if this was an ImageWriter II after the query
  549.     (**hGlobals).isImageWriterII = isImageWriterII;
  550.     
  551.     // write out the new configuration
  552.     anErr = GXWriteDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle)configHandle);
  553.     
  554.     
  555. // CLEANUP EXCEPTION HANDLING
  556. FetchStatusString:
  557. Failed_SendInitialData:
  558.     DisposHandle((Handle) configHandle);
  559.     
  560. NewHandle:
  561. Send_GXWriteData:
  562. FetchCommType:
  563.     return(anErr);
  564.     
  565. } // UpdateConfiguration
  566.  
  567.  
  568. /* ------------------------------------------------------------------------------------    */
  569. OSErr WriteDraftChars(long **draftTable, unsigned char *draftChar, long numChars)
  570. /*
  571.     This routine writes out a single character in the native set of the printer.
  572.     It uses a table that's part of the driver to do the right thing in order to generate this
  573.     character.
  574. */
  575. {
  576.     OSErr        anErr = noErr;
  577.     char        outputChars[20];                // a maximum of 20 characters can be generated
  578.     short        charCount;                    
  579.     
  580.     // For each character in the buffer, determine how to map the character to a draft character
  581.     for (; numChars > 0; --numChars, ++draftChar)
  582.     {
  583.         // No characters yet for this output character
  584.         charCount = 0;
  585.             
  586.         // Only consider characters in the printable range
  587.         if (*draftChar >= 0x20)
  588.         {
  589.             unsigned long    draftControl = (*draftTable)[*draftChar-0x20];    // Fetch native mode long word corresponding to this character
  590.             unsigned char    outChar;
  591.             unsigned char    nationalSet;
  592.             short                i;
  593.             
  594.             // For each word which composes the native mode long word 
  595.             for (i = 1; i >= 0; --i)
  596.             {
  597.                 // Should we send a backspace character (to overstrike)?
  598.                 if ( (draftControl & 0x80000000) != 0 )
  599.                     outputChars[charCount++] = 0x08;
  600.                 
  601.                 outChar = (draftControl >> 16) & 0xFF;
  602.                 if (outChar != 0)
  603.                 {
  604.                     // Determine the national character set to select
  605.                     nationalSet = (draftControl >> 24) & 0xF;    
  606.     
  607.                     //    Is this character in the standard, built-in character set?
  608.                     if (nationalSet == 0)
  609.                     {
  610.                         outputChars[charCount++] = outChar;
  611.                     }
  612.                     else    //    T => Must select a foreign language character set 
  613.                     {
  614.                         outputChars[charCount++] = 0x1B;
  615.                         outputChars[charCount++] = 0x44;
  616.                         outputChars[charCount++] = nationalSet;
  617.                         outputChars[charCount++] = 0x00;
  618.                         outputChars[charCount++] = outChar;
  619.                         outputChars[charCount++] = 0x1B;                // We always switch back to the kAmerican character set
  620.                         outputChars[charCount++] = 0x5A;
  621.                         outputChars[charCount++] = 0x07;
  622.                         outputChars[charCount++] = 0x00;
  623.                     }
  624.                 }
  625.                 
  626.                 // Take the next (low) word and process it (if we're not all done)
  627.                 draftControl <<= 16;
  628.             }    
  629.         }
  630.             
  631.         // If we generated any data, send it out now
  632.         if (charCount > 0)
  633.             anErr = Send_GXBufferData(outputChars, charCount, gxNoBufferOptions);
  634.     }
  635.         
  636.     return(anErr);    
  637.     
  638. } // WriteDraftChars
  639.  
  640. /* ------------------------------------------------------------------------------------    */
  641. OSErr GetPointerThisBig(Ptr *theBuff, long numBytes) 
  642. {
  643.     OSErr        anErr = noErr;
  644.     
  645.     if (*theBuff != nil)
  646.     {
  647.         if ( GetPtrSize(*theBuff) < numBytes )    //    T => Won't be big enough; make a new one
  648.         {
  649.             DisposPtr(*theBuff);
  650.             *theBuff = nil;
  651.         }
  652.     }
  653.  
  654.     if (*theBuff == nil)
  655.     {
  656.         *theBuff = NewPtrClear(numBytes);
  657.         anErr = MemError();
  658.     }
  659.     
  660.     return(anErr);
  661.     
  662. } // GetPointerThisBig
  663.  
  664. /* ------------------------------------------------------------------------------------    */
  665. OSErr GetTextAndPosition(    gxShape            theShape, 
  666.                             Ptr                *theChars, 
  667.                             long            *numChars, 
  668.                             gxPoint            *textPosition)
  669. {
  670.     OSErr        anErr = noErr;
  671.     long        textLength;
  672.     
  673.     // Determine the size of the text data and the position of the text
  674.     textLength = GXGetLayout(theShape, nil, nil, nil, nil, nil, nil, nil, nil, textPosition);
  675.  
  676.     // Make sure we have a buffer pointer large enough to hold all of the data
  677.     
  678.     anErr = GetPointerThisBig(theChars, textLength);
  679.     require(anErr == noErr, CantAllocTextBuff);
  680.     
  681.     // Now we retrieve the text
  682.     GXGetLayout(theShape, *theChars, nil, nil, nil, nil, nil, nil, nil, nil);
  683.     
  684.     // Remember the number of characters in the shape
  685.     *numChars = textLength;
  686.     
  687.  
  688. /******* Clean-up *******/
  689.  
  690. CantAllocTextBuff:
  691.     return(anErr);
  692.     
  693. } // GetTextAndPosition
  694.  
  695. /* ------------------------------------------------------------------------------------    */
  696. OSErr PrintPageInDraftMode(gxShape thePage, gxRasterImageDataHdl imageData)
  697. {
  698.     OSErr                    anErr = noErr;
  699.     long                    i;
  700.     long                    numItems;
  701.     Fixed                    currYPos = ff(0);
  702.     Ptr                        theChars = nil;
  703.     long                    numChars = 0;
  704.     gxPoint                    textPosition;
  705.     Fixed                    oldTextSize = ff(0);
  706.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  707.     
  708.     // Since the page picture we need to process is a picture shape that's embedded in
  709.     // thePage (a shape containing one item => a picture), we need to extract the real
  710.     // page picture from thePage.
  711.     
  712.     thePage = GetPictureItem(thePage, 1, nil, nil, nil, nil);
  713.     numItems = GXGetPicture(thePage, nil, nil, nil, nil);
  714.     
  715.     // For each shape within the picture, check its type and process it accordingly
  716.     
  717.     for (i = 1; i <= numItems; ++i)
  718.     {
  719.         gxShape                theShape;
  720.         short                theType;
  721.                 
  722.         theShape = GetPictureItem(thePage, i, nil, nil, nil, nil);
  723.         theType = GXGetShapeType(theShape);
  724.         
  725.         if (theType == gxLayoutType)    //    T => We have a layout shape
  726.         {
  727.             Fixed        textSize;
  728.             char        buff[12];
  729.             char        theFace;
  730.             short        cmndBuffSz;
  731.             
  732.             // First determine the style in which we're printing
  733.             
  734.             theFace = GetStyleCommonFace( GXGetShapeStyle(theShape) );
  735.             
  736.             buff[0] = ESCAPE;
  737.             if ( (theFace & bold) != 0 )    //    T => Turn bold facing on
  738.                 buff[1] = '!';
  739.             else                                    //    T => Turn it off
  740.                 buff[1] = '"';
  741.             
  742.             buff[2] = ESCAPE;
  743.             if ( (theFace & underline) != 0 )    //    T => Turn underline facing on
  744.                 buff[3] = 'X';
  745.             else                                            //    T => Turn it off
  746.                 buff[3] = 'Y';
  747.                 
  748.             cmndBuffSz = 4;
  749.             
  750.             // Next determine if we need to change the size of the font being used
  751.             
  752.             textSize = GXGetShapeTextSize(theShape);
  753.             if (textSize != oldTextSize)    //    T => Must issue LQ command to change font size
  754.             {
  755.                 buff[4] = ESCAPE;                //    The first escape command selects black color
  756.                 buff[5] = kSetColorCommand;
  757.                 buff[6] = '0';
  758.                 
  759.                 buff[7] = ESCAPE;                //    The second escape command selects a draft font
  760.                 buff[8] = 'a';
  761.                 buff[9] = '1';
  762.                 
  763.                 buff[10] = ESCAPE;                //    The third escape command selects the character pitch
  764.                 
  765.                 if ( textSize <= ff(10) )    //    T => Select 10 cpi
  766.                 {
  767.                     buff[11] = 'N';
  768.                 }
  769.                 else    //    T => All other sizes get mapped to 12 cpi
  770.                 {
  771.                     buff[11] = 'E';
  772.                 }
  773.                 
  774.                 // Remember the last text size
  775.                 oldTextSize = textSize;    
  776.                 
  777.                 // Adjust the size of the data to be sent to the printer
  778.                 cmndBuffSz += 8;
  779.             }
  780.             // else - no change in font size
  781.             
  782.             // Send the commands to the printer
  783.             anErr = Send_GXBufferData(buff, cmndBuffSz, gxDontSplitBuffer);
  784.             require(anErr == noErr, CantSendFontCmnd);
  785.  
  786.             // Get the ASCII text and the starting position of the data
  787.             anErr = GetTextAndPosition(theShape, &theChars, &numChars, &textPosition);
  788.             require(anErr == noErr, CantGetTextAndPos);
  789.             
  790.             if ( (currYPos != ff(0)) && (currYPos != textPosition.y) )    //    T => Moving to a lower line, finish the last ;line with a CR
  791.             {
  792.                 char        c = 0x0D;
  793.                 
  794.                 anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  795.                 require(anErr == noErr, CantSendCRCmnd);
  796.             }
  797.             
  798.             // Position the print head to the proper location on the page
  799.             {
  800.                 gxMapping                theMapping;
  801.                 long                    lineFeedSize;
  802.                 Str255                    positionCmndsBuff;
  803.                 unsigned long            bytesInBuff = 0;
  804.                 char                    *p;
  805.  
  806.                 GXGetShapeMapping(theShape, &theMapping);
  807.                 MapPoints(&theMapping, (long) 1, &textPosition);    //    Just map the first point
  808.                 
  809.                 // Now position the print head vertically
  810.  
  811.                 lineFeedSize = (textPosition.y - currYPos) >> 16;
  812.                 anErr = Send_GXRasterLineFeed(&lineFeedSize, (char *) positionCmndsBuff, &bytesInBuff, imageData);
  813.                 require(anErr == noErr, CantEmitLineFeeds);
  814.                 
  815.                 // Update the current Y position pointer on the page
  816.                 currYPos = textPosition.y;
  817.  
  818.                 // Now position the print head horizontally on the page
  819.  
  820.                 p = (char *) &positionCmndsBuff[bytesInBuff];        
  821.                 *p++ = ESCAPE;
  822.                 *p++ = 'F';
  823.                 Long2Dec((*hGlobals)->leftMargin + FixedToInt(textPosition.x), p);    // Convert left margin into ASCII and place it at the start of the scan line
  824.                 
  825.                 // Update the number of bytes in the buffer
  826.                 bytesInBuff += 6;
  827.  
  828.                 // Send the positioning info to the printer
  829.                 anErr = Send_GXBufferData((char *) positionCmndsBuff, bytesInBuff, gxDontSplitBuffer);
  830.                 require(anErr == noErr, CantSendPositionCmnds);
  831.             }
  832.             
  833.             // Now we send the text data to the printer
  834.             anErr = WriteDraftChars((long **) (*hGlobals)->draftTable, (unsigned char *) theChars, numChars);
  835.             require(anErr == noErr, CantWriteChars);
  836.         }
  837.     }    // for
  838.  
  839.     // Send one last CR to wrap the last line (if there was one)
  840.     {
  841.         char        c = 0x0D;
  842.         
  843.         anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  844.     }
  845.  
  846.  
  847. /******* Clean-up *******/
  848.  
  849. CantWriteChars:
  850. CantSendPositionCmnds:
  851. CantEmitLineFeeds:
  852. CantSendCRCmnd:
  853. CantGetTextAndPos:
  854. CantSendFontCmnd:
  855.     if (theChars != nil)
  856.         DisposPtr(theChars);
  857.                 
  858.     return(anErr);
  859.     
  860. } // PrintPageInDraftMode 
  861.  
  862. //<FF>
  863. /* ------------------------------------------------------------------------------------    */
  864. /*    SPECIFIC DRIVER UNIVERSAL OVERRIDES                                                    */
  865. /* ------------------------------------------------------------------------------------    */
  866. OSErr SD_Initialize (void) 
  867. /*
  868.     The SD_Initalize message is called when a new job is created.  The standard
  869.     thing to do is to allocate and fill out your globals as you see fit.
  870. */
  871. {
  872.  
  873.     SpecGlobalsHdl     hGlobals;
  874.     OSErr             anErr;
  875.         
  876.     // we make our globals
  877.     hGlobals = (SpecGlobalsHdl) NewHandleClear( sizeof(SpecGlobals) );
  878.     anErr = MemError();
  879.  
  880.     // and we save them away
  881.     SetMessageHandlerInstanceContext(hGlobals);
  882.  
  883.     // is everything okay?
  884.     nrequire(anErr, MNewHandleClear);
  885.     
  886.     // Don't need to initialize because of the NewHandleCLEAR
  887.     //(**hGlobals).draftTable = nil;
  888.     //(**hGlobals).lineFeeds = 0;
  889.     //(**hGlobals).packagingOptions = kNoPackagingOptions;
  890.     //(**hGlobals).idleError         = noErr;
  891.     //(**hGlobals).idleQuery         = false;
  892.     //(**hGlobals).idleTimeout         = 0;
  893.     //(**hGlobals).timeoutPending     = false;
  894.     
  895.     
  896.     return(noErr);
  897.     
  898.     
  899. /*-----EXCEPTION HANDLING------*/
  900.  
  901.  
  902. MNewHandleClear:
  903.     return(anErr);
  904.     
  905. } // SD_Initialize
  906.  
  907.  
  908. //<FF>
  909. /* ------------------------------------------------------------------------------------    */
  910. OSErr SD_ShutDown(void) 
  911. /*
  912.     Shutdown is called when the job is done with.  A good thing to do is to get
  913.     rid of any additional storage that is laying around.
  914. */
  915. {
  916.     // clean up our stuff
  917.     SpecGlobalsHdl hGlobals = GetMessageHandlerInstanceContext();
  918.  
  919.     // get rid of the draft table (if we have one)
  920.     if (hGlobals)
  921.         DisposHandle((**hGlobals).draftTable);
  922.     
  923.     // we get rid of our storage
  924.     DisposHandle((Handle) hGlobals);
  925.     
  926.     // clear out our globals - to avoid double disposes
  927.     SetMessageHandlerInstanceContext(nil);
  928.  
  929.     return(noErr);
  930.     
  931.     
  932. } // SD_ShutDown
  933.  
  934. //<FF>
  935. /* ------------------------------------------------------------------------------------    */
  936. OSErr    SD_DefaultPrinter(gxPrinter thePrinter)
  937. /*
  938.     This call is made to setup the default printer object.  The job of the
  939.     specific driver is to add in any viewDevices that it wishes applications
  940.     to be able to format specifically for.
  941. */
  942. {
  943.     OSErr            anErr;
  944.     gxViewDevice    vd;
  945.     gxJob            theJob = GXGetJob();
  946.     
  947.     // add the standard viewDevices first
  948.     anErr = Forward_GXDefaultPrinter(thePrinter);
  949.     nrequire(anErr, DefaultPrinter);
  950.     
  951.     // add a 144 b/w viewDevice
  952.     vd = NewDeviceResolutionViewDevice();
  953.     {
  954.     gxSetColor        theColors[2];
  955.     gxSetColor        *pColor;
  956.     gxColorSet        theSet;
  957.     
  958.     pColor = &theColors[0];
  959.     
  960.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0xFFFF;
  961.     
  962.     pColor++;
  963.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  964.     
  965.     theSet = GXNewColorSet(gxRGBSpace, 2, theColors);
  966.     SetViewDeviceColorSet(vd, theSet);
  967.     GXDisposeColorSet(theSet);
  968.     }
  969.         
  970.     anErr = GXAddPrinterViewDevice(thePrinter, vd);
  971.     nrequire(anErr, FailedAddBWViewDevice);
  972.  
  973.     
  974.     // add a 144 color viewDevice with 8 colors in it
  975.     //
  976.     //    Color        Index        R            G            B
  977.     //    white        0            0xFFFF        0xFFFF        0xFFFF        
  978.     //    yellow        1            0xFFFF        0xFFFF        0x0000
  979.     //    magenta        2            0xFFFF        0x0000        0xFFFF
  980.     //    red            3            0xFFFF        0x0000        0x0000
  981.     //    cyan        4            0x0000        0xFFFF        0xFFFF
  982.     //    green        5            0x0000        0xFFFF        0x0000
  983.     //    blue        6            0x0000        0x0000        0xFFFF
  984.     //    black        7            0x0000        0x0000        0x0000
  985.     
  986.     if (PrinterHasColorRibbon(thePrinter))
  987.         {
  988.         gxSetColor        theColors[8];
  989.         gxSetColor        *pColor;
  990.         gxColorSet        theSet;
  991.         short            idx;
  992.  
  993.         vd = NewDeviceResolutionViewDevice();
  994.         
  995.         pColor = &theColors[0];
  996.         for (idx = 0; idx < 8; ++idx)
  997.             {
  998.             // default the color to black
  999.             pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  1000.             
  1001.             // and give it componants to go along with this index
  1002.             if (idx & 0x04)
  1003.                 pColor->rgb.red     = 0xFFFF;
  1004.             if (idx & 0x02)
  1005.                 pColor->rgb.green     = 0xFFFF;
  1006.             if (idx & 0x01)
  1007.                 pColor->rgb.blue     = 0xFFFF;
  1008.                 
  1009.             // move on to the next color
  1010.             ++pColor;
  1011.             }
  1012.         
  1013.         theSet = GXNewColorSet(gxRGBSpace, 8, theColors);
  1014.         SetViewDeviceColorSet(vd, theSet);
  1015.         GXDisposeColorSet(theSet);
  1016.  
  1017.         anErr = GXAddPrinterViewDevice(thePrinter, vd);
  1018.         nrequire(anErr, FailedAddColorViewDevice);
  1019.         }
  1020.     
  1021.     /* Only if we are the output printer (not the formatting printer) */
  1022.     if (GXGetJobPrinter(theJob) == GXGetJobOutputPrinter(theJob)) {
  1023.         Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1024.         Handle                 jobQualitySettingsHdl;    
  1025.         gxQualityInfo        *qualitySettings;
  1026.         Ptr                    p;
  1027.         Str255                bestString, roughString;
  1028.  
  1029.         // read in our quality mode strings
  1030.         {
  1031.         short    curResFile = CurResFile();
  1032.         
  1033.         UseResFile(GXGetMessageHandlerResFile());
  1034.         
  1035.         GetIndString( bestString, kNewQualityID, kBestString);
  1036.         GetIndString( roughString, kNewQualityID, kRoughString);
  1037.         UseResFile(curResFile);
  1038.         }
  1039.         
  1040.         jobQualitySettingsHdl = NewHandle(0);
  1041.         anErr = MemError();
  1042.         nrequire(anErr, FailedNewHandle);
  1043.  
  1044.         anErr = GetCollectionItemHdl (     jobCollection,
  1045.                                         gxQualityTag,
  1046.                                         gxPrintingTagID,
  1047.                                         jobQualitySettingsHdl );
  1048.  
  1049.         if (anErr == noErr) 
  1050.             {    /* Check for proper structure -- count as not found if different */
  1051.             HLockHi(jobQualitySettingsHdl);
  1052.  
  1053.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1054.             p = qualitySettings->qualityNames;
  1055.  
  1056.             if (qualitySettings->disableQuality) 
  1057.                 anErr = collectionItemNotFoundErr;
  1058.             else if (qualitySettings->qualityCount != 2)
  1059.                 anErr = collectionItemNotFoundErr;
  1060.             else if (! IUEqualString((unsigned char const *) p, bestString))
  1061.                 anErr = collectionItemNotFoundErr;
  1062.             else if (! IUEqualString((unsigned char const *) (p + p[0] + 1), roughString))
  1063.                 anErr = collectionItemNotFoundErr;
  1064.  
  1065.             HUnlock(jobQualitySettingsHdl);
  1066.             }
  1067.  
  1068.         if (anErr == collectionItemNotFoundErr) 
  1069.             {
  1070.             Size            count;
  1071.  
  1072.             /* Create the proper quality item */
  1073.             SetHandleSize(jobQualitySettingsHdl,(sizeof(gxQualityInfo) + bestString[0] + roughString[0] + 2 ));
  1074.             anErr = MemError();
  1075.             nrequire( anErr, FailedSetHandleSize );
  1076.                 
  1077.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1078.             
  1079.             qualitySettings->disableQuality = false;
  1080.             qualitySettings->defaultQuality = 1;
  1081.             qualitySettings->currentQuality = 1;
  1082.             qualitySettings->qualityCount = 2;
  1083.  
  1084.             count = bestString[0]+1;
  1085.             p = qualitySettings->qualityNames;
  1086.             BlockMove( bestString, p, count );
  1087.  
  1088.             p += count;
  1089.             BlockMove( roughString, p, roughString[0]+1 );
  1090.  
  1091.             /* Add the proper quality item */
  1092.             anErr = AddCollectionItemHdl (     jobCollection,
  1093.                                             gxQualityTag,
  1094.                                             gxPrintingTagID,
  1095.                                             jobQualitySettingsHdl );
  1096.  
  1097.             /* Make it vilatile by driver */
  1098.             if (anErr == noErr)
  1099.                 (void) SetCollectionItemInfo(jobCollection, gxQualityTag, gxPrintingTagID, 0x0000FFFF, gxVolatileOutputDriverCategory);
  1100.  
  1101.             }
  1102.         
  1103. FailedSetHandleSize:
  1104.         DisposHandle(jobQualitySettingsHdl);
  1105.     }
  1106. FailedNewHandle:
  1107.     
  1108.     ncheck(noErr);
  1109.     return(noErr);
  1110.     
  1111.     
  1112.     
  1113. // EXCEPTION HANDLING
  1114. FailedAddColorViewDevice:
  1115. FailedAddBWViewDevice:
  1116.     GXDisposeViewDevice(vd);
  1117.     
  1118. DefaultPrinter:
  1119.     return(anErr);
  1120.     
  1121. } // SD_DefaultPrinter
  1122.  
  1123. //<FF>
  1124. /* ------------------------------------------------------------------------------------    */
  1125.  
  1126. OSErr SD_DefaultFormat(gxFormat theFormat)
  1127. {
  1128.     OSErr                anErr;
  1129.     Handle                 jobQualitySettingsHdl;    
  1130.     
  1131.     anErr = Forward_GXDefaultFormat(theFormat);
  1132.     
  1133.     // now, if the application has set up a special formatting mode, we need to update
  1134.     // the quality mode collection item (and any private ones we use)
  1135.     if (anErr == noErr)
  1136.         {
  1137.         gxPoint                dpiPoint;
  1138.         gxMapping            vdMapping;
  1139.         gxViewDevice        selectedDevice = GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 0);
  1140.         
  1141.         
  1142.         dpiPoint.x = ff(72);
  1143.         dpiPoint.y = ff(72);
  1144.         
  1145.         if (selectedDevice != GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 1) )
  1146.             {
  1147.             GXGetViewDeviceMapping(selectedDevice, &vdMapping);
  1148.             MapPoints(&vdMapping, 1, &dpiPoint);
  1149.             
  1150.             {
  1151.             Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1152.             gxQualityInfo        *qualitySettings;
  1153.     
  1154.             jobQualitySettingsHdl = NewHandle(0);
  1155.             anErr = MemError();
  1156.             nrequire(anErr, FailedNewHandle);
  1157.  
  1158.             anErr = GetCollectionItemHdl (     jobCollection,
  1159.                                                 gxQualityTag,
  1160.                                                  gxPrintingTagID,
  1161.                                                jobQualitySettingsHdl );
  1162.  
  1163.             nrequire(anErr, FailedGetCollectionItemHdl);
  1164.  
  1165.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1166.  
  1167.             qualitySettings->currentQuality = 
  1168.                 (dpiPoint.y > ff(100)) ? (qualitySettings->qualityCount-1) : 0;
  1169.  
  1170.             anErr = AddCollectionItemHdl (     jobCollection,
  1171.                                             gxQualityTag,
  1172.                                             gxPrintingTagID,
  1173.                                             jobQualitySettingsHdl );
  1174.                                                  
  1175.             DisposHandle(jobQualitySettingsHdl);
  1176.             }
  1177.  
  1178.         
  1179.             if (anErr == noErr)
  1180.                 {
  1181.                 long    formatOptions;
  1182.                 
  1183.                 // turn off super-res
  1184.                 formatOptions = 0;
  1185.                 anErr = AddCollectionItem(GXGetFormatCollection(theFormat), 
  1186.                     DriverCreator, 0,
  1187.                     sizeof(formatOptions),
  1188.                     &formatOptions);
  1189.                 }
  1190.             }
  1191.         }
  1192.  
  1193. FailedNewHandle:        
  1194.     ncheck(anErr);
  1195.     return(anErr);
  1196.  
  1197. FailedGetCollectionItemHdl:
  1198.     DisposHandle(jobQualitySettingsHdl);
  1199.     return(anErr);
  1200.     
  1201. } // SD_DefaultFormat
  1202.  
  1203. //<FF>
  1204. /* ------------------------------------------------------------------------------------    */
  1205. OSErr SD_DefaultJob()
  1206. /*
  1207.     We override this message to add our default - highest res possible
  1208. */
  1209. {
  1210.     OSErr    anErr;
  1211.     
  1212.     anErr = Forward_GXDefaultJob();
  1213.     if (anErr == noErr)
  1214.         {
  1215.         long        imagewriterOptions = kSuperRes;
  1216.         
  1217.         anErr = AddCollectionItem(GXGetJobCollection(GXGetJob()), 
  1218.                     DriverCreator,
  1219.                     0,
  1220.                     sizeof(imagewriterOptions),
  1221.                     &imagewriterOptions);
  1222.                     
  1223.         }
  1224.  
  1225.  
  1226.     return(anErr);
  1227.     
  1228. } // SD_DefaultJob
  1229.  
  1230. /* ------------------------------------------------------------------------------------    */
  1231. OSErr SD_OpenConnection(void)
  1232. /*
  1233.     The OpenConnection message is sent in order to open the connection to the device.
  1234. */
  1235. {
  1236.     OSErr    anErr;
  1237.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1238.     
  1239.     // how to process idle events
  1240.     (**hGlobals).idleError         = noErr;
  1241.     (**hGlobals).idleQuery         = false;
  1242.     (**hGlobals).idleTimeout     = 0;
  1243.     (**hGlobals).timeoutPending = false;
  1244.     
  1245.     // first, open the connection the standard way
  1246.     anErr = Forward_GXOpenConnection();
  1247.     nrequire(anErr, OpenConnection);
  1248.     
  1249.     // then, bring the configuration file up to date
  1250.     anErr = UpdateConfiguration();
  1251.     nrequire(anErr, UpdateConfiguration);
  1252.     
  1253.     return(noErr);
  1254.     
  1255. // EXCEPTION HANDLING
  1256. UpdateConfiguration:
  1257.     GXCleanupOpenConnection();
  1258.     
  1259. OpenConnection:
  1260.  
  1261.     return(anErr);
  1262.     
  1263. } // SD_OpenConnection
  1264.  
  1265. /* ------------------------------------------------------------------------------------    */
  1266. OSErr SD_CloseConnection(void)
  1267. {
  1268.     unsigned short    statusReturn;
  1269.     OSErr            anErr, anErr2;
  1270.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1271.     ResType            commType = (**hGlobals).commType;
  1272.  
  1273.     if (commType == 'PPTL')
  1274.         {
  1275.         // flush out all data so that we can query the printer properly    one last time
  1276.         anErr = Send_GXWriteData(nil, 0);
  1277.         nrequire(anErr, Send_GXWriteData1);
  1278.         
  1279.         // for PAP: bring the configuration file up to date & check that the printer is online
  1280.         anErr2 = UpdateConfiguration();
  1281.         if (anErr == noErr) anErr = anErr2;
  1282.         }
  1283.     else
  1284.         {
  1285.         // for serial: flush out all data so that we can query the printer properly    one last time
  1286.         anErr = Send_GXWriteData(nil, 0);
  1287.         nrequire(anErr, Send_GXWriteData2);
  1288.  
  1289.         // one last time check up on printer status 
  1290.         if ((**hGlobals).isImageWriterII)
  1291.             {
  1292.             anErr2 = FetchStatusString(&statusReturn, false, true);
  1293.             if (anErr == noErr) anErr = anErr2;
  1294.             }
  1295.         }
  1296.     
  1297. Send_GXWriteData2:
  1298. Send_GXWriteData1:
  1299. FetchStatusString:
  1300.     // close the connection the standard way
  1301.     anErr2 = Forward_GXCloseConnection();
  1302.     if (anErr == noErr) anErr = anErr2;
  1303.         
  1304.     return(anErr);
  1305.     
  1306. } // SD_CloseConnection
  1307.  
  1308. /* ------------------------------------------------------------------------------------    */
  1309. OSErr SD_JobIdle()
  1310. {
  1311.     OSErr            anErr = noErr;
  1312.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1313.     SpecGlobalsPtr    pGlobals;
  1314.     
  1315.     pGlobals = *hGlobals;
  1316.     if ( (pGlobals->idleQuery) && (pGlobals->commType == 'PPTL') )
  1317.         {
  1318.         unsigned short    statusReturn;
  1319.  
  1320.         pGlobals->idleQuery = false;
  1321.         
  1322.         anErr = FetchStatusString(&statusReturn, true, true);
  1323.         nrequire(anErr, FetchStatusString);
  1324.  
  1325.         anErr = Forward_GXJobIdle();
  1326.  
  1327.         // EXCEPTION HANDLING
  1328.         FetchStatusString:
  1329.             pGlobals = *hGlobals;
  1330.             pGlobals->idleQuery = true;
  1331.         }
  1332.     else    
  1333.         anErr = Forward_GXJobIdle();
  1334.     
  1335.     // if we continue looping here too long during the initial query -- give the user
  1336.     // a chance to bail or correct the problem
  1337.     pGlobals = *hGlobals;
  1338.     if ( (!(pGlobals->timeoutPending)) && (pGlobals->idleTimeout != 0) )
  1339.         {
  1340.         if (TickCount() > pGlobals->idleTimeout)
  1341.             {
  1342.             gxStatusRecord        theStat;
  1343.             gxStatusRecord        *pStat = &theStat;
  1344.             
  1345.             pStat->statusOwner    = 'drvr';
  1346.             pStat->statResId     = kDriverStatus;        
  1347.             pStat->statResIndex = kCheckOnline;            
  1348.             pStat->bufferLen      = 0;
  1349.             pStat->dialogResult = 0;
  1350.                         
  1351.             // tell the user to check the printer
  1352.             pGlobals->timeoutPending = true;
  1353.             (void) GXAlertTheUser(pStat);
  1354.             pGlobals = *hGlobals;
  1355.             pGlobals->timeoutPending = false;
  1356.                 
  1357.             // based on the user's response cancel
  1358.             switch (pStat->dialogResult)
  1359.                 {
  1360.                 case ok:
  1361.                     pGlobals->idleTimeout = TickCount() + kQueryTimeout;
  1362.                     break;
  1363.                     
  1364.                 case cancel:
  1365.                     pGlobals->idleError = gxPrUserAbortErr;
  1366.                     break;
  1367.                     
  1368.                 case 3:
  1369.                     pGlobals->idleError = kPutJobOnHoldErr;
  1370.                     break;
  1371.                 }
  1372.  
  1373.             // display "sending data to the printer" message
  1374.             if (anErr == noErr)
  1375.                 anErr = GXReportStatus(kDriverStatus, kSendingData);
  1376.             }
  1377.         }
  1378.         
  1379.     if (anErr == noErr)
  1380.         anErr = pGlobals->idleError;
  1381.         
  1382.     return(anErr);
  1383.     
  1384. } // SD_JobIdle
  1385.  
  1386. /* ------------------------------------------------------------------------------------    */
  1387. OSErr SD_FreeBuffer(gxPrintingBuffer * theBuffer)
  1388. {
  1389.     OSErr            anErr = noErr;
  1390.     OSErr            firstError = noErr;
  1391.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1392.     
  1393.  
  1394.     if ((**hGlobals).commType == 'PPTL')
  1395.         {
  1396.         unsigned short    statusReturn;
  1397.  
  1398.         anErr = FetchStatusString(&statusReturn, true, true);
  1399.         nrequire(anErr, FetchStatusString);
  1400.         }
  1401.         
  1402.     do
  1403.         {
  1404.         // we can idle query now if we need to    
  1405.         (**hGlobals).idleQuery = true;
  1406.  
  1407.         // try to send the buffer again
  1408.         anErr = Forward_GXFreeBuffer(theBuffer);
  1409.         if (firstError == noErr)
  1410.             firstError = anErr;
  1411.     
  1412.         (**hGlobals).idleQuery = false;
  1413.  
  1414.         // timeout dialog!
  1415.         if (anErr == gxAioTimeout)
  1416.             {
  1417.             gxStatusRecord        theStat;
  1418.             gxStatusRecord        *pStat = &theStat;
  1419.             
  1420.             pStat->statusOwner    = 'drvr';
  1421.             pStat->statResId     = kDriverStatus;        
  1422.             pStat->statResIndex = kCheckOnline;            
  1423.             pStat->bufferLen      = 0;
  1424.             pStat->dialogResult = 0;
  1425.                         
  1426.             // tell the user to check the printer
  1427.             (void) GXAlertTheUser(pStat);
  1428.                 
  1429.             // based on the user's response cancel
  1430.             switch (pStat->dialogResult)
  1431.                 {
  1432.                 case ok:
  1433.                     anErr = gxAioTimeout;
  1434.                     break;
  1435.                     
  1436.                 case cancel:
  1437.                     anErr = gxPrUserAbortErr;
  1438.                     break;
  1439.                     
  1440.                 case 3:
  1441.                     anErr = kPutJobOnHoldErr;
  1442.                     break;
  1443.                 }
  1444.             }
  1445.             
  1446.         } while (anErr == gxAioTimeout);
  1447.     
  1448.     // put down the timeout dialog, if we ever put one up
  1449.     if (firstError != noErr)
  1450.         (void) GXReportStatus(kDriverStatus, kSendingData);
  1451.  
  1452.     // error to return from next idle
  1453.     (**hGlobals).idleError = anErr;
  1454.     
  1455. FetchStatusString:        
  1456.     return(anErr);
  1457.     
  1458. } // SD_FreeBuffer
  1459.  
  1460. /* ------------------------------------------------------------------------------------    */
  1461. OSErr SD_DumpBuffer(gxPrintingBuffer * theBuffer)
  1462. {
  1463.     OSErr    anErr;
  1464.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1465.         
  1466.     if ((**hGlobals).commType == 'PPTL')
  1467.         {
  1468.         unsigned short    statusReturn;
  1469.         anErr = FetchStatusString(&statusReturn, true, true);
  1470.         nrequire(anErr, FetchStatusString);
  1471.         }
  1472.     anErr = Forward_GXDumpBuffer(theBuffer);
  1473.  
  1474. FetchStatusString:        
  1475.     return(anErr);
  1476.     
  1477. } // SD_DumpBuffer
  1478.  
  1479. /* ------------------------------------------------------------------------------------    */
  1480. OSErr SD_StartSendPage(gxFormat pageFormat)
  1481. /*
  1482.     The StartSendPage message is sent just before the page begins to be rendered.
  1483.     
  1484.     Note that the StartSendPage message will not be sent until imaging/communication
  1485.     time, so that user interaction alerts are considered okay here
  1486. */
  1487. {
  1488.     OSErr                        anErr = noErr;
  1489.     gxJob                        theJob = GXGetJob();
  1490.     Collection                    jobCollection;
  1491.     gxPaperType                    thePaperType;
  1492.     gxTrayFeedInfo                trayFeedInfo;
  1493.     long                        itemSize = sizeof(trayFeedInfo);
  1494.     ResType                        commType;
  1495.     unsigned short                statusReturn;
  1496.     
  1497.     check(theJob);
  1498.     jobCollection = GXGetJobCollection(theJob);
  1499.     check(jobCollection);
  1500.     
  1501.     // cache communications type
  1502.     commType = (**(SpecGlobalsHdl)GetMessageHandlerInstanceContext()).commType;
  1503.     if (commType == 'PPTL')
  1504.         {
  1505.         anErr = FetchStatusString(&statusReturn, true, true);
  1506.         nrequire(anErr, FetchStatusString);
  1507.         }
  1508.     else
  1509.         statusReturn = 0;
  1510.         
  1511.     // check to see if this particular page is to be manually fed
  1512.     anErr = GetCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, &itemSize, &trayFeedInfo);
  1513.     nrequire(anErr, FailedGetCollectionItem);
  1514.             
  1515.     // manual feed or out of paper?  Time to ask the user what to do
  1516.     if     (     trayFeedInfo.manualFeedThisPage
  1517.         ||  ( ( (statusReturn & kOutOfPaperMask) != 0 ) )
  1518.         )
  1519.         {
  1520.         // Wait for all IO to complete, so that we can correctly tell the user what to do.
  1521.         // Since the WriteData message makes sure all data is flushed before performing the
  1522.         // IO, this call insures that pending IO is complete.
  1523.         anErr = Send_GXWriteData(nil, 0);
  1524.         nrequire(anErr, FlushAllData);
  1525.  
  1526.  
  1527.         // then, conduct the alert with the user
  1528.         {
  1529.         gxStatusRecord        *pStat;
  1530.         
  1531.         // make a status record containing the request to the user - note that 
  1532.         // we have to make room for ManualFeedRecord OR OutOfPaperRecord, but manual is bigger
  1533.         pStat = (gxStatusRecord *)NewPtrClear(sizeof(gxStatusRecord)  + sizeof(gxManualFeedRecord));
  1534.         anErr = MemError();
  1535.         nrequire(anErr, NewPtrClear);
  1536.                 
  1537.         pStat->statusOwner    = 'univ';
  1538.         pStat->statResId     = gxUnivAlertStatusResourceId;    // we use the built-in status for this
  1539.         pStat->dialogResult = 0;
  1540.         
  1541.         if (trayFeedInfo.manualFeedThisPage)
  1542.             {
  1543.             gxManualFeedRecord    *pFeed;
  1544.             
  1545.             pStat->statResIndex = gxUnivManualFeedIndex;            // status meaning "manual feed alert"
  1546.             pStat->bufferLen      = sizeof(gxManualFeedRecord);
  1547.             pFeed = (gxManualFeedRecord*)&pStat->statusBuffer;
  1548.         
  1549.             // we can switch to autofeed if we want - and tell the user what kind of paper to load in
  1550.             pFeed->canAutoFeed = true;
  1551.             GXGetPaperTypeName(thePaperType = GXGetFormatPaperType(pageFormat), pFeed->paperTypeName);
  1552.             }
  1553.         else
  1554.             {
  1555.             gxOutOfPaperRecord    *pOut;
  1556.             
  1557.             pStat->statResIndex = gxUnivOutOfPaperIndex;            // status meaning "manual feed alert"
  1558.             pStat->bufferLen      = sizeof(gxOutOfPaperRecord);
  1559.             
  1560.             pOut = (gxOutOfPaperRecord*)&pStat->statusBuffer;
  1561.             GXGetPaperTypeName(GXGetFormatPaperType(pageFormat), pOut->paperTypeName);
  1562.             }
  1563.             
  1564.         // keep sending the user the alert until either
  1565.         //  a) the problem resolves itself
  1566.         //  b) the user responds via the dialog
  1567.         //  c) some other (fatal) error happens
  1568.         do
  1569.             {
  1570.             
  1571.             // tell the user
  1572.             anErr = GXAlertTheUser(pStat);
  1573.             
  1574.             // if the paper got suddenly loaded, do an OK
  1575.             if (commType == 'PPTL')
  1576.                 {
  1577.                 (void) FetchStatusString(&statusReturn, true, true);
  1578.                 if ((statusReturn & kOutOfPaperMask) == 0)
  1579.                     {
  1580.                     pStat->dialogResult = ok;
  1581.                     anErr = noErr;
  1582.                     }
  1583.                 }
  1584.                 
  1585.             } while ((anErr == noErr) && (pStat->dialogResult == 0));
  1586.  
  1587.         // based on the user's response, continue, cancel, or switch to auto feed
  1588.         switch ( pStat->dialogResult )
  1589.             {
  1590.             case ok:
  1591.                 // paper is loaded
  1592.                 break;
  1593.                 
  1594.             case cancel:
  1595.                 // user wishes to stop the printing process
  1596.                 anErr = gxPrUserAbortErr;
  1597.                 break;
  1598.                 
  1599.             case gxAutoFeedButtonId:
  1600.                 // do rest of job with auto feed
  1601.                 
  1602.                 {
  1603.                 gxPaperFeedInfo paperFeed;
  1604.                 
  1605.                 /* Update for job */
  1606.                 paperFeed.autoFeed = true;
  1607.                 (void) AddCollectionItem(jobCollection, gxPaperFeedTag, gxPrintingTagID, sizeof(paperFeed), &paperFeed);
  1608.                 }
  1609.                 
  1610.                 /* Update as it may be reused */
  1611.                 trayFeedInfo.manualFeedThisPage = false;    /* Other trayInfo fields are still valid */
  1612.                 (void) AddCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, sizeof(trayFeedInfo), &trayFeedInfo);
  1613.                 
  1614.                 /* Can pass paper type reference as this IS device communication time */
  1615.                 anErr = Send_GXCheckStatus((Ptr) &thePaperType, sizeof(thePaperType), 0, 'univ');
  1616.                 ncheck(anErr);
  1617.                 
  1618.                 /* No need to reset tray from gxTrayFeedInfo.feedTrayIndex as there is only one tray! */
  1619.                 break;
  1620.                 
  1621.             } // switch
  1622.             
  1623.             
  1624.         // done with the status now
  1625.         DisposPtr((Ptr) pStat);
  1626.         }
  1627.             
  1628.         } // if manual feed job
  1629.         
  1630.     // display "sending data to the printer" message
  1631.     if (anErr == noErr)
  1632.         anErr = GXReportStatus(kDriverStatus, kSendingData);
  1633.         
  1634.     nrequire(anErr, FailedWaitForPaper);
  1635.         
  1636.     // continue with the standard starting of the page
  1637.     anErr = Forward_GXStartSendPage(pageFormat);
  1638.         
  1639.         
  1640. // FALL THROUGH AND HANDLE EXCEPTIONS
  1641.  
  1642. FailedWaitForPaper:
  1643. NewPtrClear:
  1644. FlushAllData:
  1645. FailedGetCollectionItem:
  1646. FetchStatusString:
  1647.     return(anErr);
  1648.     
  1649. } // SD_StartSendPage
  1650.  
  1651. /* ------------------------------------------------------------------------------------    */
  1652. OSErr SD_FinishSendPage()
  1653. {
  1654.     OSErr        anErr = noErr;
  1655.     Str63        formLength;            // should be more than big enough for form skipping
  1656.     char        len = 0;
  1657.  
  1658.     // we may have issued line feeds RIGHT up to the end of the page.  If
  1659.     // we do that and then issue a form feed, we'll kick out a blank page.
  1660.     // to avoid that, we back up a tad and then let the normal form feed
  1661.     // go through.  Option 2 would be to track each and every motion control
  1662.     // we send to the printer -- but that's more work than this.  In addition,
  1663.     // this method makes sure we are synced up exactly to the hardware
  1664.     formLength[len++] = ESCAPE;
  1665.     formLength[len++] = 'T';
  1666.     formLength[len++] = '0';
  1667.     formLength[len++] = '1';
  1668.     formLength[len++] = ESCAPE;
  1669.     formLength[len++] = 'r';
  1670.     formLength[len++] = 0x0A;
  1671.     
  1672.     // reset to forward motion for the form feed
  1673.     formLength[len++] = ESCAPE;
  1674.     formLength[len++] = 'f';
  1675.     
  1676.     anErr = Send_GXBufferData((char *) &formLength[0], len, gxNoBufferOptions );
  1677.     nrequire(anErr, Send_GXBufferData);
  1678.     
  1679.     // Default implementation provides the actual form feed
  1680.     anErr = Forward_GXFinishSendPage();
  1681.     
  1682. // FALL THROUGH EXCEPTION HANDLING
  1683. Send_GXBufferData:
  1684.  
  1685.     return(anErr);
  1686.     
  1687. } // SD_FinishSendPage
  1688.  
  1689. /* ------------------------------------------------------------------------------------    */
  1690. OSErr SD_JobFormatDialog(gxDialogResult*    theResult)
  1691. /*
  1692.     This message is sent in response to the user's request to put up a formatting dialog
  1693. */
  1694. {
  1695.     OSErr                     anErr;
  1696.     gxJobFormatModeTableHdl    theJobFormatModeList;
  1697.     long                    i;
  1698.     gxJob                     theJob = GXGetJob();
  1699.     
  1700.     // set up the JobFormatMode information
  1701.     
  1702.     anErr = GXGetAvailableJobFormatModes(&theJobFormatModeList);
  1703.     if ((!anErr) && (theJobFormatModeList))
  1704.         {
  1705.         for (i = 0; i <= (*theJobFormatModeList)->numModes - 1; ++i) 
  1706.             {
  1707.             if ((*theJobFormatModeList)->modes[i] == gxTextJobFormatMode) 
  1708.                 {
  1709.                 GXSetPreferredJobFormatMode(gxTextJobFormatMode, false);
  1710.                 break;
  1711.                 }
  1712.             }
  1713.         DisposHandle((Handle)theJobFormatModeList);
  1714.         }
  1715.         
  1716.     // do the normal dialogs after handling the job format mode stuff
  1717.     return(Forward_GXJobDefaultFormatDialog(theResult));
  1718.     
  1719. } // SD_JobFormatModeQuery
  1720.  
  1721. /* ------------------------------------------------------------------------------------    */
  1722. OSErr SD_JobFormatModeQuery(    gxQueryType        theQuery,
  1723.                                 void*            srcData,
  1724.                                 void*            dstData)
  1725. /*
  1726.     This message is sent to find out information about the current job format mode.
  1727. */
  1728. {
  1729.     OSErr        anErr = noErr;
  1730.     Handle        theFonts;
  1731.     Handle        theStyles;
  1732.     
  1733.     check(dstData != nil);
  1734.     
  1735.     // What type of query is being requested?
  1736.     switch(theQuery) 
  1737.     {
  1738.         case gxSetStyleJobFormatCommonStyleQuery:
  1739.         {
  1740.             char                *pStyleName;
  1741.  
  1742.             // Fetch the list of supported styles
  1743.             
  1744.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1745.             require(anErr == noErr, FailedToLoadStyles1);
  1746.             
  1747.             HNoPurge(theStyles);
  1748.             HLock(theStyles);
  1749.             
  1750.             // Determine which style is being referenced and set the corresponding style (only 2 styles
  1751.             // are currently supported)
  1752.             
  1753.             if (**((short **) theStyles) == 2)    //    T => We have the correct number of styles
  1754.             {
  1755.                 char        whichFace = 0;
  1756.                 
  1757.                 pStyleName = ((char *) *theStyles) + sizeof(short); 
  1758.                 
  1759.                 if ( IUCompString((unsigned char const *) pStyleName, srcData) == 0 )    //    T => They want bold face
  1760.                 {
  1761.                     whichFace = bold;
  1762.                 }
  1763.                 else
  1764.                 {
  1765.                     // Point to the next name in the list
  1766.                     pStyleName += *pStyleName + 1;
  1767.  
  1768.                     if ( IUCompString((unsigned char const *) pStyleName, srcData) == 0 )    //    T => They want underline face
  1769.                     {
  1770.                         whichFace = underline;
  1771.                     }
  1772.                 }
  1773.  
  1774.                 //    If the client specified a valid face, set it now
  1775.                 if (whichFace != 0)
  1776.                 {
  1777.                     SetStyleCommonFace((gxStyle) dstData, GetStyleCommonFace((gxStyle) dstData) | whichFace);
  1778.                 }
  1779.             }
  1780.             // else - something is wrong with our resource
  1781.             
  1782.             // Dump the temporary handle
  1783.             DisposHandle(theStyles);
  1784.             
  1785.             break;
  1786.         }
  1787.             
  1788.         case gxGetJobFormatFontCommonStylesQuery:
  1789.         {
  1790.             short                numStyles;
  1791.             short                i;
  1792.             char                *pStyleName;
  1793.  
  1794.             // Fetch the list of supported styles
  1795.             
  1796.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1797.             require(anErr == noErr, FailedToLoadStyles2);
  1798.             
  1799.             HNoPurge(theStyles);
  1800.             HLock(theStyles);
  1801.             
  1802.             // Determine the number of styles in the list
  1803.             numStyles = **((short **) theStyles);
  1804.  
  1805.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the styles
  1806.                 SetHandleSize(*(Handle *)dstData, sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1807.             else
  1808.                 *(Handle *)dstData = NewHandle(sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1809.             
  1810.             anErr = MemError();
  1811.             require(anErr == noErr, StyleTableResizeFailed);
  1812.             
  1813.             // Now extract the name of each of the supported fonts
  1814.             
  1815.             for (i = 1, pStyleName = ((char *) *theStyles) + sizeof(short); i <= numStyles; ++i, pStyleName += *pStyleName + 1)
  1816.             {
  1817.                 BlockMove(pStyleName, (*((gxStyleNameTableHdl) *(Handle *)dstData))->styleNames[i - 1], *pStyleName + 1);
  1818.             }
  1819.             
  1820.             (*((gxStyleNameTableHdl) *(Handle *)dstData))->numStyleNames = numStyles;
  1821.             
  1822.             // Dump the temporary handle
  1823.             DisposHandle(theStyles);
  1824.             
  1825.             break;
  1826.         }
  1827.             
  1828.         case gxGetJobFormatLineConstraintQuery:            //    This type of query is not supported
  1829.             if (*(Handle *)dstData != nil)
  1830.                 SetHandleSize(*(Handle *)dstData, 0);        // Don't return any data
  1831.             break;
  1832.             
  1833.         case gxGetJobFormatFontsQuery:
  1834.         {
  1835.             short                numFonts;
  1836.             short                i;
  1837.             char                *pFontName;
  1838.  
  1839.             // Fetch the list of supported fonts
  1840.             
  1841.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeFontsID, &theFonts);
  1842.             require(anErr == noErr, FailedToLoadFonts);
  1843.             
  1844.             HNoPurge(theFonts);
  1845.             HLock(theFonts);
  1846.             
  1847.             // Determine the number of fonts in the list
  1848.             numFonts = **((short **) theFonts);
  1849.  
  1850.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the fonts
  1851.                 SetHandleSize(*(Handle *)dstData, sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1852.             else
  1853.                 *(Handle *)dstData = NewHandle(sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1854.             
  1855.             anErr = MemError();
  1856.             require(anErr == noErr, FontTableResizeFailed);
  1857.             
  1858.             // Now generate a reference to each of the supported fonts
  1859.             
  1860.             for (i = 1, pFontName = ((char *) *theFonts) + sizeof(short); i <= numFonts; ++i, pFontName += *pFontName + 1)
  1861.             {
  1862.                 gxFont            thisFont;
  1863.                 gxFontTable        *pFontTable;
  1864.             
  1865.                 thisFont = FindPNameFont(gxFullFontName, (unsigned char const *) pFontName);
  1866.                 
  1867.                 pFontTable = *((gxFontTableHdl) *(Handle *)dstData);
  1868.                 pFontTable->fonts[i - 1] = thisFont;
  1869.             }
  1870.             
  1871.             (*((gxFontTableHdl) *(Handle *)dstData))->numFonts = numFonts;
  1872.             
  1873.             // Dump the temporary handle
  1874.             DisposHandle(theFonts);
  1875.  
  1876.             break;
  1877.         }
  1878.             
  1879.         case gxGetJobFormatFontConstraintQuery:
  1880.         {
  1881.             gxPositionConstraintTable        *pPositionTable;
  1882.             
  1883.             if ( *(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on position constraints
  1884.                 SetHandleSize(*(Handle *)dstData, sizeof(gxPositionConstraintTable) + sizeof(Fixed));
  1885.             else
  1886.                 *(Handle *)dstData = NewHandle( sizeof(gxPositionConstraintTable) + sizeof(Fixed) );
  1887.             
  1888.             pPositionTable = *((gxPositionConstraintTableHdl) *(Handle *)dstData);
  1889.             
  1890.             pPositionTable->phase.x     = 0;                //    Start at the top left corner of the page
  1891.             pPositionTable->phase.y     = 0;
  1892.             pPositionTable->offset.x     = ff(12);        // Indent from the top left by a six lines per inch margin
  1893.             pPositionTable->offset.y     = ff(12);         
  1894.             pPositionTable->numSizes     = 2;                // Two font sizes supported
  1895.             pPositionTable->sizes[0]     = ff(10);         // 10 pitch
  1896.             pPositionTable->sizes[1]     = ff(12);         // 12 pitch
  1897.             
  1898.             break;
  1899.         }
  1900.     } // switch
  1901.     
  1902.     return(anErr);
  1903.     
  1904.  
  1905. /******* Clean-up *******/
  1906.  
  1907. StyleTableResizeFailed:
  1908.     DisposHandle((Handle) theStyles);
  1909.     return(anErr);
  1910.  
  1911. FontTableResizeFailed:
  1912.     DisposHandle((Handle) theFonts);
  1913.  
  1914. FailedToLoadStyles1:
  1915. FailedToLoadStyles2:
  1916. FailedToLoadFonts:
  1917.     return(anErr);
  1918.     
  1919. } // SD_JobFormatModeQuery
  1920.  
  1921. //<FF>
  1922. /* ------------------------------------------------------------------------------------    */
  1923. OSErr SD_SetupImageData(
  1924.     gxRasterImageDataHdl hImageData)        // raster image data stuff
  1925. /*
  1926.     This message is called to setup the constant data used for imaging the entire job.
  1927. */
  1928. {
  1929.  
  1930.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  1931.     OSErr                        anErr;
  1932.     gxRasterImageDataPtr        pImageData;
  1933.     Boolean                     isJobNotFinalQuality, isTextJobFormatMode;
  1934.     long                        imagewriterOptions;
  1935.     
  1936.     // do the default setup
  1937.     anErr = Forward_GXSetupImageData(hImageData);
  1938.     nrequire(anErr, Forward_GXSetupImageData);
  1939.     
  1940.     // test for 'final' quality mode
  1941.     isJobNotFinalQuality = !JobIsBest(&imagewriterOptions);
  1942.     
  1943.     // test for textJobFormatMode
  1944.     isTextJobFormatMode = ( GXGetJobFormatMode( GXGetJob() ) == gxTextJobFormatMode);
  1945.             
  1946.     // if the job is not final quality or using textJobFormatMode, downgrade the imaging data to our lower quality
  1947.     if (isJobNotFinalQuality  ||  isTextJobFormatMode)
  1948.         {
  1949.         // ROUGH OR TEXT MODE
  1950.         
  1951.         // dereference for size and speed    
  1952.         pImageData = *hImageData;
  1953.                 
  1954.         // image at 80 or 72 dpi
  1955.         if (imagewriterOptions & kSuperRes)
  1956.             pImageData->hImageRes = ff(80);
  1957.         else
  1958.             pImageData->hImageRes = ff(72);
  1959.         pImageData->vImageRes = ff(72);
  1960.         
  1961.         // textJobFormatMode loads up the draft table, else setup halftones
  1962.         if (isTextJobFormatMode)
  1963.             {
  1964.             Handle            draftTable;
  1965.  
  1966.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID, &draftTable);
  1967.             nrequire(anErr, FailedToLoadDraftTable);
  1968.             
  1969.             // store away the draft table
  1970.             (**hGlobals).draftTable = draftTable;
  1971.  
  1972.             // Download something?    
  1973.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID+1, &draftTable);
  1974.             if (anErr == resNotFound)
  1975.                 {
  1976.                 draftTable = nil;
  1977.                 anErr = noErr;
  1978.                 }
  1979.             nrequire(anErr, GetDownloadTable);    
  1980.         
  1981.             if (draftTable)
  1982.                 {
  1983.                 HLock(draftTable);
  1984.                 anErr = Send_GXBufferData(*draftTable, GetHandleSize(draftTable), gxDontSplitBuffer);
  1985.                 DisposHandle(draftTable);
  1986.                 nrequire(anErr, SendDownloadTable);
  1987.                 }
  1988.             }
  1989.         else
  1990.             {            
  1991.             // use dither level that will look better at 72 dpi 
  1992.             // resolution than our default values (MAYBE: 4 is the default now anyway)
  1993.             pImageData->theSetup.planeSetup[0].planeHalftone.method = 4;
  1994.             
  1995.             // of course, turn off color matching when in non-final mode!
  1996.             pImageData->theSetup.planeSetup[0].planeProfile = nil;
  1997.             }
  1998.             
  1999.         if (isJobNotFinalQuality)
  2000.             {
  2001.             if (imagewriterOptions & kSuperRes)
  2002.                 {
  2003.                 // use bidirectional instead of unidirectional
  2004.                 // and also <esc>N instead of <esc>p for quality mode
  2005.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+3;
  2006.                 }
  2007.             else
  2008.                 {
  2009.                 // use bidirectional instead of unidirectional
  2010.                 // and also <esc>n instead of <esc>p for quality mode
  2011.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+2;
  2012.                 }
  2013.             }
  2014.         
  2015.         // packaging data
  2016.         pImageData->packagingInfo.headHeight         = 8;        // 8 pins (instead of 16)
  2017.         pImageData->packagingInfo.numberPasses         = 1;        // in 1 head pass (instead of 2)
  2018.         pImageData->packagingInfo.passOffset         = 0;        // with no space between passes
  2019.         }
  2020.     else
  2021.         {
  2022.         // FINAL QUALITY
  2023.         
  2024.         // dereference for size and speed    
  2025.         pImageData = *hImageData;
  2026.                 
  2027.         // image at 160 or 144 dpi
  2028.         if (imagewriterOptions & kSuperRes)
  2029.             {
  2030.             pImageData->hImageRes = ff(160);
  2031.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+1;
  2032.             }
  2033.         else
  2034.             {
  2035.             pImageData->hImageRes = ff(144);
  2036.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+0;
  2037.             }
  2038.         }
  2039.     
  2040.     // not a color ribbon?  Setup for black and white - do a B/W halftone rather than a dither
  2041.     if (!PrinterHasColorRibbon(GXGetJobOutputPrinter(GXGetJob())))
  2042.         {
  2043.         // dereference for size and speed    
  2044.         pImageData = *hImageData;
  2045.  
  2046.         // one plane, no color flags, move the halftone info up into correct position
  2047.         pImageData->theSetup.planes = 1;
  2048.         pImageData->theSetup.depth = 1;
  2049.         pImageData->packagingInfo.colorPasses = 1;
  2050.         pImageData->packagingInfo.packageOptions = 0;
  2051.         pImageData->theSetup.planeSetup[0].planeSpace = gxNoSpace;
  2052.         pImageData->theSetup.planeSetup[0].planeSet = nil;
  2053.         pImageData->theSetup.planeSetup[0].planeProfile = nil;
  2054.         pImageData->theSetup.planeSetup[0].planeOptions = gxDefaultOffscreen;
  2055.         pImageData->theSetup.planeSetup[0].planeHalftone.method = gxRoundDot;
  2056.         pImageData->theSetup.planeSetup[0].planeHalftone.tintSpace = gxRGBSpace;
  2057.         }
  2058.  
  2059.     return(noErr);
  2060.     
  2061. // EXCEPTION HANDLING
  2062. SendDownloadTable:
  2063. GetDownloadTable:
  2064.     DisposHandle((**hGlobals).draftTable);
  2065.     (**hGlobals).draftTable = nil;
  2066.     
  2067. FailedToLoadDraftTable:
  2068. Forward_GXSetupImageData:
  2069.     return(anErr);
  2070.     
  2071. } // SD_SetupImageData
  2072.  
  2073. /* ------------------------------------------------------------------------------------    */
  2074. OSErr SD_FetchDriverData(
  2075.     ResType            theType,
  2076.     short            theID,
  2077.     Handle*            theData)
  2078. {
  2079.  
  2080.     OSErr    anErr;
  2081.     
  2082.     anErr = Forward_GXFetchTaggedDriverData(theType, theID, theData);
  2083.     
  2084.     // do the translation at the proper DPI by modifying the old API
  2085.     // customization resource
  2086.     if ( (anErr   == noErr)    &&                 // got the resource okay
  2087.          (theType == 'cust')   &&                // it was a customization resource 
  2088.          (theID   == -8192)   )                    // with the old API id
  2089.         {
  2090.         long imagewriterOptions;
  2091.         
  2092.         if (!JobIsBest(&imagewriterOptions))
  2093.             {
  2094.             **((short**)theData)   = 72;
  2095.             **((short**)theData+1) = 72;
  2096.             }
  2097.         }
  2098.         
  2099.     return(anErr);
  2100.     
  2101. } // SD_FetchDriverData
  2102.  
  2103.  
  2104. /* ------------------------------------------------------------------------------------    */
  2105. OSErr SD_RenderPage(    gxFormat                theFormat,
  2106.                         gxShape                    thePage,
  2107.                         gxPageInfoRecord        *pageInfo,
  2108.                         gxRasterImageDataHdl    imageInfo)
  2109. /*
  2110.     The message sent to render an entire page.
  2111. */
  2112. {
  2113.  
  2114.     OSErr    theError = noErr;
  2115.  
  2116.     // if not text mode, do it the normal (raster) way
  2117.     if (GXGetJobFormatMode(GXGetJob()) != gxTextJobFormatMode) 
  2118.         {
  2119.         gxRectangle            paperSize;
  2120.         Str63                formLength;            // should be more than big enough for form skipping
  2121.         char                aNumber[8];
  2122.         char                len = 0;
  2123.         short                formLen;            // form length (in 144 dpi)
  2124.         short                i;
  2125.         
  2126.         
  2127.         // find out how big our paper is
  2128.         GXGetPaperTypeDimensions(GXGetFormatPaperType(theFormat), nil, &paperSize);
  2129.         
  2130.         // determine the left margin (in pixels)
  2131.         {
  2132.         SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  2133.         SpecGlobalsPtr            pGlobals;
  2134.         gxRasterImageDataPtr    pImageData;
  2135.  
  2136.         check(hGlobals);
  2137.  
  2138.         // dereference for size and speed    
  2139.         pImageData     = *imageInfo;
  2140.         pGlobals = *hGlobals;
  2141.         paperSize.left += ff(18);        // ImageWriter's can't go tighter than .25 inch
  2142.         if (paperSize.left > 0)
  2143.             paperSize.left = 0;
  2144.         pGlobals->leftMargin     = FixedToInt(
  2145.                                     FixMul(-paperSize.left, 
  2146.                                         FixDiv(pImageData->hImageRes, ff(72))));
  2147.         
  2148.         // set this to be the top of form
  2149.         formLength[len++] = ESCAPE;
  2150.         formLength[len++] = 'v';
  2151.  
  2152.         // set the form length to be the size of the page iff ImageWriterII
  2153.         if (pGlobals->isImageWriterII)
  2154.             {
  2155.             formLength[len++] = ESCAPE;
  2156.             formLength[len++] = 'H';
  2157.             formLen = FixedToInt(FixMul(paperSize.bottom-paperSize.top, ff(2)) );    // length is set in 144 dpi
  2158.             NumToString(formLen, (unsigned char *) aNumber);
  2159.             for (i = 0; i < 4-aNumber[0]; ++i)
  2160.                 formLength[len++] = '0';
  2161.             for (i = 1; i <= aNumber[0]; ++i)
  2162.                 formLength[len++] = aNumber[i];
  2163.             }
  2164.         }
  2165.  
  2166.         // NOW: move over the top margin
  2167.         formLen = -FixedToInt( FixMul(paperSize.top, ff(2)) );
  2168.         
  2169.             // Forward line feed
  2170.             formLength[len++] = ESCAPE;
  2171.             formLength[len++] = 'f';
  2172.  
  2173.             // send multiples of 99
  2174.             if (formLen >= 99)
  2175.                 {
  2176.                 formLength[len++] = ESCAPE;
  2177.                 formLength[len++] = 'T';
  2178.                 formLength[len++] = '9';
  2179.                 formLength[len++] = '9';
  2180.                 while (formLen >= 99)
  2181.                     {
  2182.                     formLength[len++] = 0x0A;        // line feed
  2183.                     
  2184.                     formLen -= 99;
  2185.                     }
  2186.                 }
  2187.                 
  2188.             // send remaining line feeds
  2189.             if (formLen > 0)
  2190.                 {
  2191.                 formLength[len++] = ESCAPE;
  2192.                 formLength[len++] = 'T';
  2193.                 NumToString(formLen, (unsigned char *) aNumber);
  2194.                 if (aNumber[0] == 1)
  2195.                     {
  2196.                     formLength[len++] = '0';
  2197.                     formLength[len++] = aNumber[1];
  2198.                     }
  2199.                 else
  2200.                     {
  2201.                     formLength[len++] = aNumber[1];
  2202.                     formLength[len++] = aNumber[2];
  2203.                     }
  2204.                 formLength[len++] = 0x0A;        // line feed
  2205.                 }
  2206.  
  2207.  
  2208.         // we've got all of this data, now send it
  2209.         theError = Send_GXBufferData((char *) &formLength[0], len, gxNoBufferOptions );
  2210.         nrequire(theError, SetFormLength);        
  2211.                 
  2212.         // continue with normal rendering
  2213.         theError = Forward_GXRenderPage(theFormat, thePage, pageInfo, imageInfo);
  2214.         } 
  2215.     else 
  2216.         {
  2217.         theError = PrintPageInDraftMode(thePage, imageInfo);
  2218.         }
  2219.  
  2220. failed_WrongShape:
  2221. SetFormLength:
  2222.     return(theError);
  2223.     
  2224. } // SD_RenderPage
  2225.  
  2226.  
  2227. //<FF>
  2228. /* ------------------------------------------------------------------------------------    */
  2229. /*    SPECIFIC DRIVER RASTER OVERRIDES                                                    */
  2230. /* ------------------------------------------------------------------------------------    */
  2231. OSErr SD_LineFeed (
  2232.     short *lineFeedSize,                         // amount to line feed by
  2233.     Ptr buffer, unsigned long    * bufferPos,     // data goes here
  2234.     gxRasterImageDataHdl hImageData)            // raster image data stuff
  2235. /*
  2236.     Message is sent to output paper advance commands to the printer
  2237. */
  2238. {
  2239.  
  2240.     OSErr    anErr;
  2241.     Boolean    amLowRes;
  2242.     long    actualLineFeed = *lineFeedSize;
  2243.     
  2244.     amLowRes = ((**hImageData).vImageRes == ff(72));
  2245.     // if we are in low res mode, we double the line feed size, as all ImageWriter 
  2246.     // line feed commands are expressed at 144 dpi.
  2247.     if (amLowRes)
  2248.         *lineFeedSize <<= 1;
  2249.     
  2250.     // optimize small motions (particularlly -1 followed by +1 with no data between)
  2251.     // into groups.  This gets rid of the "paper dance" for blank colors passes.
  2252.     {    
  2253.     SpecGlobalsHdl    hGlobals = GetMessageHandlerInstanceContext();
  2254.     SpecGlobalsPtr    pGlobals = *hGlobals;
  2255.     
  2256.     if (    (pGlobals->packagingOptions == kDoSmallLineFeeds) || 
  2257.             (*lineFeedSize < -1) || 
  2258.             (*lineFeedSize > 1) )
  2259.         {
  2260.         *lineFeedSize += pGlobals->lineFeeds;
  2261.         pGlobals->lineFeeds = 0;
  2262.         // do the line feed in the default way
  2263.         anErr = Forward_GXRasterLineFeed(&actualLineFeed, buffer, bufferPos, hImageData);
  2264.         }
  2265.     else
  2266.         {
  2267.         pGlobals->lineFeeds += *lineFeedSize;
  2268.         *lineFeedSize = 0;
  2269.         anErr = noErr;
  2270.         }
  2271.     }
  2272.     
  2273.     // and if in low quality mode, we divide the result to make up for the multiplication
  2274.     // that we do above
  2275.     if (amLowRes)
  2276.         *lineFeedSize >>= 1;    
  2277.             
  2278.     return(anErr);
  2279.     
  2280. } // SD_LineFeed
  2281.  
  2282. //<FF>
  2283. /* ------------------------------------------------------------------------------------    */
  2284. OSErr SD_PackageBitmap (
  2285.     gxRasterPackageBitmapRec    *pPackage,
  2286.     Ptr                         buffer,     // data goes here + bufferPos
  2287.     unsigned long                 *bufferPos,    // how much of the buffer already is full
  2288.     gxRasterImageDataHdl         hImageData)    // private image data
  2289. /*
  2290.     Packages a bitmap for the ImageWriter
  2291.     This routine is called in order to add your rotated and packaged pixel
  2292.     data to the buffer.  It is called once for each head pass.  This routine
  2293.     is pretty complex because it also does IW run length compression.  
  2294.     
  2295.     It must do the following:
  2296.         
  2297.     1)    Start filling the buffer from buffer+bufferPos.  Remember
  2298.         that this pointer may not be word aligned - so be careful
  2299.         assigning things into it.
  2300.         
  2301.     2)    If your printer does SetMargins, put a "fake" set of commands at
  2302.         the begining of the data.  Since most of the time you don't
  2303.         know the margins, you can save away the value of the bufferPos,
  2304.         and backpatch it after you have finished with the offscreen.
  2305.         SetMargins is used on printers that allow you to not send starting
  2306.         and ending whitespace.
  2307.         
  2308.     3)    Add in the rotated data for your printer.  The data to stuff starts
  2309.         at location startY in hOffscreen.  Stuff the bits from here until
  2310.         you reach startY+<your band size>, which is the size of your single
  2311.         band in this resolution mode.  Increment your number by 
  2312.         <your pass offset> + 1, which is the number of microspaces
  2313.         you will send between head passes to form this band.   Take care
  2314.         that you don't step off of the end of the offscreen in this operation,
  2315.         you may be called with startY at the end of the offscreen if the first part
  2316.         of the band is white.
  2317.         
  2318.         colorBand contains the color band which you should be stuffing, from
  2319.         1 to the number of color passes your printer needs (usually 4).
  2320.         Pack in the correct color band.  The packager will call you once
  2321.         for each color band, and correctly handle line feeds and backward
  2322.         line feeds to do the correct thing.  If your printer takes full
  2323.         RGB or CYMK data, I would define your number of colors to be
  2324.         1 and pack the full RGB or CYMK data with the one call to StuffBuffers.
  2325.         
  2326.         If you request kSendAllColors in your raster pack resource, then this
  2327.         message will always be called for all color passes, even those that
  2328.         do not have data on them.  For some printers, this is useful.  For the
  2329.         case of the ImageWriter, this option is not specified, so this message
  2330.         will only be sent for colors that actually have dirty bits within them.
  2331.         
  2332.     4)    Backpatch SetMargins from your saved value in step 2) now that you
  2333.         know the margins.
  2334.         
  2335.     5)    Increment bufferPos by the number of bytes you have
  2336.         added to the buffer.  Be sure to take into account the Set Margins
  2337.         command if you added one.
  2338.  
  2339.     
  2340. */
  2341. {
  2342. #pragma unused (isColorDirty)
  2343.  
  2344.     OSErr                    anErr;                    // would you beleive we could make mistakes?
  2345.     ScanLinePtr                pTheScanLine;            // Pointer to the start of scan line data
  2346.     unsigned short            lastDirtyCol;            // Last dirty part of the scan line
  2347.     unsigned short            firstDirty;                // First dirty pixel
  2348.     unsigned short            lastDirty;                // Last dirty pixel
  2349.     Boolean                    bandIsDirty;            // Is this band dirty?
  2350.     unsigned short            numberBytesAdded;        // Number of bytes we have added to the row
  2351.     unsigned short            repeatCount;            // Number of times we have seen this bitmap
  2352.     
  2353.     register unsigned short    whichCol;                // Index into the scan line data
  2354.     register unsigned short    x,y;                    // Index values into the offscreen
  2355.         
  2356.     register Ptr            thePtr;                    // Pointer to each Y scanline
  2357.     register unsigned char    tempColumn;                // Placeholder for the working column
  2358.     unsigned char            lastColumn;                // What was in the contents of the last column?
  2359.     
  2360.     Ptr                        basePtr;                // Pointer to current X byte
  2361.     unsigned char            outputMask;                // Mask of bit to set in rotated image
  2362.     unsigned char            inputMask;                // Mask of bit to look at in X
  2363.     unsigned char            startingInputMask;        // Mask of first bit of interest
  2364.     unsigned short            yPointerOffset;            // Increment pointer by this to get to next scanline
  2365.     
  2366.     unsigned short            endY, endX, incrY;        // To remove loop invariants.
  2367.     unsigned short            packingColor;            // number of colors packing
  2368.     unsigned long             originalBufferPos;        // where we were in the buffer before we started;
  2369.     long                    originalLineFeeds;        // how many line feeds did we have before?
  2370.     SpecGlobalsHdl            hGlobals = GetMessageHandlerInstanceContext();
  2371.     SpecGlobalsPtr            pGlobals = *hGlobals;
  2372.     
  2373. /* This macro stores one group into the pointer:
  2374.     P = Pointer to fill into
  2375.     G = Character for group
  2376.     S = Length of group run in pixels
  2377. */
  2378. #define EMITGROUP(P, G, S)                    \
  2379.         P->cEscape = ESCAPE;                \
  2380.         P->cCommand = G;                    \
  2381.         Long2Dec(S, P->cLineLength);        
  2382.  
  2383.     // save away original position in order to do a restore should the band be clean
  2384.     originalBufferPos = *bufferPos;
  2385.     originalLineFeeds = pGlobals->lineFeeds;
  2386.     if (originalLineFeeds == 0)
  2387.         {
  2388.         anErr = noErr;
  2389.         }
  2390.     else
  2391.         {
  2392.         // if we have any extra line feeds saved up, do them now!    
  2393.         pGlobals->lineFeeds = 0;
  2394.         pGlobals->packagingOptions = kDoSmallLineFeeds;
  2395.         anErr = Send_GXRasterLineFeed(&originalLineFeeds, buffer, bufferPos, hImageData);
  2396.         pGlobals = *hGlobals;
  2397.         pGlobals->packagingOptions = kNoPackagingOptions;
  2398.         }
  2399.     nrequire(anErr, SendInitialLineFeeds);
  2400.     
  2401.     /* Set color iff ImageWriterII */
  2402.     if ((**hGlobals).isImageWriterII)
  2403.         {
  2404.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos));
  2405.         
  2406.         /* Set color mode for this scan line, if needed */
  2407.         pTheScanLine->cColorEscape        = ESCAPE;
  2408.         pTheScanLine->cSetColorCommand    = kSetColorCommand;
  2409.         
  2410.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2411.         if (packingColor == 4)
  2412.             switch (pPackage->colorBand)
  2413.                 {
  2414.                 case 1: // yellow
  2415.                     pTheScanLine->cColor    = '1';
  2416.                     startingInputMask = 0x10;
  2417.                     break;
  2418.                     
  2419.                 case 2: // magenta
  2420.                     pTheScanLine->cColor    = '2';
  2421.                     startingInputMask = 0x20;
  2422.                     break;
  2423.     
  2424.                 case 3: // cyan
  2425.                     pTheScanLine->cColor    = '3';
  2426.                     startingInputMask = 0x40;
  2427.                     break;
  2428.                     
  2429.                 case 4: // black
  2430.                     pTheScanLine->cColor    = '0';
  2431.                     startingInputMask = 0x80;
  2432.                     break;
  2433.                     
  2434.                 }
  2435.         else
  2436.             {
  2437.             pTheScanLine->cColor = '0';
  2438.             startingInputMask = 0x80;
  2439.             }
  2440.         }
  2441.     else    /* Backup to eliminate cColorEscape, cSetColorCommand and cColor */
  2442.         {
  2443.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos) - 3);
  2444.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2445.         startingInputMask = 0x80;
  2446.         }
  2447.  
  2448.     /* Start with the first bit in the offscreen */
  2449.     inputMask = startingInputMask;
  2450.         
  2451.     /* We start out with no dirty bits */
  2452.     firstDirty = 0;
  2453.     lastDirty = 0;
  2454.     bandIsDirty = false;
  2455.     
  2456.     /* Set our array index to zero */
  2457.     whichCol = 0;
  2458.     lastDirtyCol = 0;
  2459.     numberBytesAdded = 0;
  2460.     
  2461.     /* Set up RLL variables */
  2462.     repeatCount = 0;
  2463.     lastColumn = 0;
  2464.     
  2465.     /* Get the byte pointer for the start of this color band */
  2466.     basePtr = pPackage->bitmapToPackage->image;
  2467.     
  2468.     /* Get the byte pointer for the start of the first scan line */ 
  2469.     basePtr += pPackage->startRaster * pPackage->bitmapToPackage->rowBytes;
  2470.             
  2471.     /* Save away loop invariants */
  2472.     endY     = pPackage->startRaster + (*hImageData)->packagingInfo.headHeight;        // Ending scan line
  2473.     incrY     = (*hImageData)->packagingInfo.passOffset + 1;            // Number of scanlines to increment by
  2474.     endX     = pPackage->dirtyRect.right;                                // Ending X pos
  2475.     yPointerOffset = incrY * pPackage->bitmapToPackage->rowBytes;            // amount to add to the input
  2476.                                                             // pointer to move to the next scanline
  2477.  
  2478.     /* If the ending position is too large for the bitmap we have been given,
  2479.        truncate it, so that we don't print garbage */
  2480.     if (endY > pPackage->bitmapToPackage->height)
  2481.         endY = pPackage->bitmapToPackage->height;
  2482.     
  2483.     /* For the entire width of the offscreen, move a rolling mask along in the
  2484.        X direction, rotating up 8 bits of Y data per column.  In addition, compress
  2485.        runs of columns that are > 14 length. */
  2486.     for (x = 0; x < endX; x++)
  2487.         {        
  2488.         /* The bits in this column are clear to begin with */
  2489.         tempColumn = 0;
  2490.         
  2491.         /* Which byte to look at in the input buffer */
  2492.         thePtr = basePtr;
  2493.         
  2494.         /*     Where to place the bit in the output. The ImageWriter takes the bit
  2495.             pattern upside down. */
  2496.         outputMask = 0x01;
  2497.         
  2498.         /* Scan through this band, setting each of the 8 bits == the bit in that scan line */
  2499.         for (y = pPackage->startRaster; y < endY; y += incrY)
  2500.             {
  2501.             /* If we have a bit in the input, rotate it into the output */
  2502.             if ((*thePtr) & inputMask)
  2503.                 tempColumn |= outputMask;
  2504.  
  2505.             // move onto next position in the output data                
  2506.             outputMask <<= 1;
  2507.             
  2508.             // move onto the next scan line in the input data
  2509.             thePtr += yPointerOffset;
  2510.             } // for y
  2511.             
  2512.             
  2513.         /* Save the column info */ 
  2514.         pTheScanLine->iTheData[whichCol] = tempColumn;
  2515.         
  2516.         /* Get the next bit from the current pointer */
  2517.         inputMask >>= packingColor;
  2518.         if (!inputMask)
  2519.             {
  2520.             /* If we run out of bits, get the next byte */
  2521.             basePtr++;
  2522.             
  2523.             /* And reset the bit mask to the first bit */
  2524.             inputMask = startingInputMask;
  2525.             }
  2526.             
  2527.         /* If we have some form of data */
  2528.         if (tempColumn != 0)
  2529.             {
  2530.             if (!bandIsDirty)
  2531.                 {
  2532.                 /* This is the first dirty pixels we have so far */
  2533.                 bandIsDirty = true;
  2534.                 firstDirty = x;
  2535.                 }
  2536.             
  2537.             /* This is also the last dirty pixels so far */
  2538.             lastDirty = x;
  2539.             } // SetDirty
  2540.             
  2541.         /* If we have some dirty bits */
  2542.         if (bandIsDirty)
  2543.             {
  2544.             /* Move on to the next column */
  2545.             whichCol++;
  2546.             
  2547.             /* If this is a dirty column, then it is the last one so far */
  2548.             if (tempColumn != 0)
  2549.                 lastDirtyCol = whichCol;
  2550.             
  2551.             /* If we have a duplication, up the repeat count */
  2552.             if (tempColumn == lastColumn) // if (false) // turn off repeat groups
  2553.                 {
  2554.                 repeatCount++;
  2555.                 if (repeatCount == 14)
  2556.                     {
  2557.                     /* Kick out the old group */
  2558.                     whichCol -= 14;
  2559.                         EMITGROUP(pTheScanLine, kGraphicsCommand, whichCol);
  2560.                         numberBytesAdded += whichCol + kGroupSize;
  2561.                         pTheScanLine = (ScanLinePtr)(((Ptr) pTheScanLine) +
  2562.                             whichCol + kGroupSize);
  2563.                     
  2564.                     whichCol = 1;
  2565.                     lastDirtyCol = 1;
  2566.                     pTheScanLine->iTheData[0] = tempColumn;
  2567.                     }
  2568.                 }
  2569.             else
  2570.                 {
  2571.                 /* If we were repeating, emit the repeat group */
  2572.                 if (repeatCount >= 14)
  2573.                     {
  2574.                     EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2575.                     numberBytesAdded += 1 + kGroupSize;
  2576.                     pTheScanLine = (ScanLinePtr) (((Ptr) pTheScanLine) + 
  2577.                         1 + kGroupSize);
  2578.                         
  2579.                     whichCol = 1;
  2580.                     lastDirtyCol = 1;
  2581.                     pTheScanLine->iTheData[0] = tempColumn;
  2582.                     }
  2583.                 repeatCount = 0;
  2584.                 lastColumn = tempColumn;
  2585.                 }
  2586.                 
  2587.             } // BandIsDirty
  2588.             
  2589.         } // end of loop for width of bitmap
  2590.  
  2591.     /* if we have a dirty band - emit the final bit of data we have
  2592.        packaged up */
  2593.     if (bandIsDirty)
  2594.         {            
  2595.         
  2596.         /* Set the margins to be the first and last dirty pixels in the scan line -
  2597.            the ImageWriter only does left margin optimization. */
  2598.         {
  2599.             SetMarginsPtr        marginBuffer;
  2600.             SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  2601.             
  2602.             check(hGlobals);
  2603.             
  2604.             /* Get the location for placing the set margin command */
  2605.             marginBuffer = (SetMarginsPtr) (buffer + (*bufferPos));
  2606.             
  2607.             /* Stuff in the set margin command */
  2608.             marginBuffer->cEscape  = ESCAPE;
  2609.             marginBuffer->cCommand = kSetMarginsCommand;
  2610.             
  2611.             /* convert left margin into ASCII and place it at the start of the buffer */
  2612.             Long2Dec((**hGlobals).leftMargin + firstDirty, (Ptr)(marginBuffer->cIndentDistance));
  2613.         }
  2614.         
  2615.         /* Send the last group command */
  2616.         if (repeatCount < 14)
  2617.             {
  2618.             /* Emit a normal group */
  2619.             EMITGROUP(pTheScanLine, kGraphicsCommand, lastDirtyCol);
  2620.             numberBytesAdded += lastDirtyCol + kGroupSize;
  2621.             }
  2622.         else
  2623.             {
  2624.             /* Don't stuff a final repeat group if it's blank space */
  2625.             if (tempColumn != 0)
  2626.                 {
  2627.                 /* Emit a repeat group */
  2628.                 EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2629.                 numberBytesAdded += 1 + kGroupSize;
  2630.                 }
  2631.             } // end of repeatCount < 14
  2632.                     
  2633.         
  2634.         /*    Increment the count of the buffer by bytes added for groups, plus
  2635.             the header, if any, plus the set margins command */
  2636.         (*bufferPos) += numberBytesAdded + kScanLineSize + kSetMarginsSize;
  2637.  
  2638.         /* and put a <cr> at the end of the line */
  2639.         *(char*)(buffer + (*bufferPos)) = '\n';
  2640.         (*bufferPos) += 1;
  2641.         
  2642.         } // bandIsDirty
  2643.     else
  2644.         {
  2645.         // don't output data if we didn't have any!
  2646.         *bufferPos = originalBufferPos;
  2647.  
  2648.         // restore original number of line feeds
  2649.         pGlobals = *hGlobals;
  2650.         pGlobals->lineFeeds = originalLineFeeds;
  2651.         } // band is not dirty
  2652.         
  2653.     // always return your errors!
  2654. SendInitialLineFeeds:
  2655.     return(anErr);
  2656.     
  2657. } // SD_PackageBitmap
  2658.